Fill a vector with random numbers c++

后端 未结 8 1244
难免孤独
难免孤独 2020-12-14 17:55

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

相关标签:
8条回答
  • 2020-12-14 18:29

    You are calling the wrong index in your vector

    Try doing:

    cout << myVector[i] << endl;
    

    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.

    0 讨论(0)
  • 2020-12-14 18:30

    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 :

    cout << b << endl;
    

    But really you should size the vector, and just access by index.

    int vec_size = rand() % 20 + 1;
    vec<int> myvec(vec_size);
    for( int i = 0; i < vec_size; ++i ) {
        vec[i] = rand() % 20 + 1;
    }
    
    /* output the list after you made it */
    std::copy(myvec.begin(), myvec.end(),
            std::ostream_iterator<int>(cout, "\n"));
    
    0 讨论(0)
提交回复
热议问题