about vector in c++ [closed]
i wanna make a function that generates a list of random numbers with a size inserted by the user to apply some sorting algorithms on these rando开发者_JS百科ms why this code doesn't run ..plz help
vector<int> DataList;
int GenerateRandomList(int min, int max, int size)
{
srand ( time(NULL) );
for(int i=0;i<size;i++)
{
DataList[i]=rand()% max+min;
cout<<DataList[i];
cout<<endl;
}
}
Your vector is empty, you cannot assign to non-existing elements.
Simply replace DataList[i] = ...
with DataList.push_back(...)
and it should work.
Also, rand() % max + min
will not do what you want, because there are only max - min + 1
numbers between min
and max
(inclusive). rand() % (max - min + 1) + min
should work.
Also, srand
should be called once at the beginning of main
and then never again. Otherwise, you may get the same sequence of numbers if you call GenerateRandomList
twice in a row.
Also, why is the function declared to return an int
? You should either change that to void
or std::vector<int>
and return the numbers you just generated instead of having a global vector.
A good way to do this is by using std::generate
. The example on the linked page covers your problem.
In your particular case, you would have to use a functor:
struct GenerateRandomList {
GenerateRandomList(int min, int max)
: min(min), max(max)
{
srand(time(NULL));
}
int operator()() const {
// this is courtesy of @FredOverflow's answer
return rand() % (max - min + 1) + min;
}
private:
int min;
int max;
};
// for generating
std::vector<int> DataList(10);
std::generate(DataList.begin(), DataList.end(), GenerateRandomList(10, 20));
You can see a working example here. The advantage of this approach is, that you can generate random numbers for any kind of container (arrays, lists, vectors, sets).
I think your problem is you want to do push_back(int) instead of doing DataList[i]=rand()% max+min;. The following code compiles and does exactly what i think you are trying to do.
#include <vector>
#include <stdlib.h>
#include <iostream>
using namespace std;
vector<int> DataList;
int GenerateRandomList(int min, int max, int size) {
srand ( time(NULL) );
for(int i=0;i<size;i++) {
DataList.push_back(rand()% max+min);
cout<<DataList[i];
cout<<endl;
}
}
int main() {
GenerateRandomList(0,15,10);
}
精彩评论