#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 {0, 2};
auto gen = [&dist, &mersenne_engine](){
return dist(mersenne_engine);
};
vector<int> vec(30);
generate(begin(vec), end(vec), gen);
// Optional
for (auto i : vec) {
cout << i << " ";
}
}
I am trying to create a vector of 30 numbers consisting of values 0-2 and each integer occurs 10 times. What is the most efficient way to do this in C++.
Basically it should be done as written in the comments.
std::vector
with the given sizeThe resulting code is simple and efficient. Please see: