Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill a vector with random numbers c++

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.

like image 375
Valrok Avatar asked Feb 02 '14 21:02

Valrok


People also ask

How do you generate a random number in a vector?

In order to have different random vectors each time, run this program, the idea is to use srand() function. Otherwise, the output vector will be the same after each compilation. Syntax: void srand(unsigned seed): This function seeds the pseudo-random number generator used by rand() with the value seed.

How do you fill a random number vector in C++?

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.


1 Answers

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 <vector>  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); 
like image 74
Marko Tunjic Avatar answered Sep 19 '22 10:09

Marko Tunjic