Fill a vector with random numbers c++

后端 未结 8 1242
难免孤独
难免孤独 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:27

    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 
    #include 
    #include 
    #include 
    #include 
    
    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 dist {1, 52};
    
        auto gen = [&dist, &mersenne_engine](){
                       return dist(mersenne_engine);
                   };
    
        vector 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);
    

提交回复
热议问题