I've got a vector that I'm trying to fill up with random numbers. I keep running into an issue however that the vector mostly outputs 0 each time that I'm running it (it shouldn't output a 0 ever). What am I doing wrong in my code written below to make it output 0 (it outputs 0 more so than any other number):
vector<int> myVector;
srand((unsigned)time(NULL));
int a = rand() % 20 + 1; //1 to 20
for (int i =0; i < a; i++){
int b = rand() % 20 + 1;
myVector.push_back(b);
cout << myVector[b] << endl;
}
I am a beginner and have not done much C++ programming in a long time so I'm not sure what is making my code malfunction. If someone could explain what I've done wrong it would be greatly appreciated.
Just adding my 2 cents... This response is similar to the one given by Marko Tunjic, but it doesn't use
std::rand
from C, but C++11 features instead. It allows you to use the distribution of your choice,uniform_int_distribution
in the example below.You are calling the wrong index in your vector
You are calling the wrong index in your vector
Try doing:
else you will risk running off the end of your vertex for the first 20 or so iterations.
You can also call .back() on your vector to get the last item in the vector.
You can use std::generate algorithm to fill a vector of n elements with random numbers.
In modern C++ it’s recommended not to use any time-based seeds and std::rand, but instead to use random_device to generate a seed. For software-based engine, you always need to specify the engine and distribution. Read More..
If you want to rearrange the elements of a range in a random order:
What about simply:
Its not clear what you are trying to do with the loop, the code is creating a vector of random size, filled with random numbers.
You are outputting "myVector[b]", but 'b' is the random value, not the index of just added number. You could just :
But really you should size the vector, and just access by index.