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 22:54

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.

#include <algorithm>
#include <iostream>
#include <limits>
#include <random>
#include <vector>

static std::vector<int> generate_data(size_t size)
{
    using value_type = int;
    // We use static in order to instantiate the random engine
    // and the distribution once only.
    // It may provoke some thread-safety issues.
    static std::uniform_int_distribution<value_type> distribution(
        std::numeric_limits<value_type>::min(),
        std::numeric_limits<value_type>::max());
    static std::default_random_engine generator;

    std::vector<value_type> data(size);
    std::generate(data.begin(), data.end(), []() { return distribution(generator); });
    return data;
}

int main()
{
    for (auto i = 0u; i < 5; ++i)
    {
        std::vector<int> myVector = generate_data(10);
        myVector = generate_data(10);

        std::cout << "myVector (iteration " << i << "): ";
        for (auto v: myVector)
        {
            std::cout << v << ",";
        }
        std::cout << "\n";
    }
}
查看更多
forever°为你锁心
3楼-- · 2019-01-22 22:58

You are calling the wrong index in your vector

cout << myVector[i] << endl;
查看更多
乱世女痞
4楼-- · 2019-01-22 23:03

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.

查看更多
走好不送
5楼-- · 2019-01-22 23:04

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..

#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <functional>

using namespace std;

int main()
{
    // First create an instance of an engine.
    random_device rnd_device;
    // Specify the engine and distribution.
    mt19937 mersenne_engine {rnd_device()};  // Generates random integers
    uniform_int_distribution<int> dist {1, 52};

    auto gen = [&dist, &mersenne_engine](){
                   return dist(mersenne_engine);
               };

    vector<int> vec(10);
    generate(begin(vec), end(vec), gen);

    // Optional
    for (auto i : vec) {
        cout << i << " ";
    }


}

If you want to rearrange the elements of a range in a random order:

  std::shuffle(begin(vec), end(vec), mersenne_engine);
查看更多
虎瘦雄心在
6楼-- · 2019-01-22 23:13

What about simply:

std::vector<int> v(1000);
std::generate(v.begin(), v.end(), std::rand);
查看更多
Summer. ? 凉城
7楼-- · 2019-01-22 23:14

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"));
查看更多
登录 后发表回答