Fill a vector with random numbers c++

2019-01-22 22:40发布

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.

8条回答
相关推荐>>
2楼-- · 2019-01-22 23:18
// here I generate a vector that contains random vectors
// for example, after this code, vec = { {1,4,8}, {1,3,6,7,9}, {2,5,6} }

#include <vector>
#include <time.h>

void generate_random_vectors(const int num_of_rand_vectors, vector<vector<int>> &vec) {
    for (int j = 0; j < num_of_rand_vectors; ++j) {
        // the vector size will be randomal: between 0 to 19
        int vec_size = (rand() % 20);
        vector<int> rand_vec(vec_size);
        for (int k = 0; k < vec_size; ++k) {
            // each vec element will be randomal: between 1 to 20
            rand_vec[k] = 1 + (rand() % 20);
        }
        // each vector will be sorted if you want to
        sort(rand_vec.begin(), rand_vec.end());
        // push each of the 'num_of_rand_vectors'-th vectors into vec
        vec.push_back(rand_vec);
    }
}

void main() {

    srand(static_cast<unsigned int>(time(NULL)));

    // input vector containing random sorted vectors
    vector<vector<int>> vec;
    generate_random_vectors(3, vec);
}
查看更多
相关推荐>>
3楼-- · 2019-01-22 23:18
cout << myVector[b] ?!

it should be : cout << myVector[i];

查看更多
登录 后发表回答