Printing out and loading vectors with random numbers

I am new to C++. I am trying to load and printout a vector with random numbers, but the output doesn't end, it keeps going on forever. How do I fix it ? I suspect, it has something to do with the size() method.

#include <iostream>
#include <vector>
using namespace std;
int main () {
vector<int> myVector(20);
srand(time(NULL));
for (int i = 0; i < myVector.size(); i++){
        int b = rand() % 20 + 1;
        myVector.push_back(b);
        cout << myVector[i] << endl;
    }
return 0;
}

1 answer

  • answered 2017-06-17 19:43 Ajax1234

    As @Rabbid76 pointed out, your vector is growing as you push more variables back into it, and that means your for loop will keep iterating because its upper bound is MyVector.size(), which is constantly increasing. Try this:

    vector<int>my_vector;
    
    int val = 20;
    
    for (int i = 0; i < val; i++)
    {
       int random_number = rand()%20 + 1;
       my_vector.push_back(random_number);
    }