choose random from vector c++ code example
Example 1: create random vectors c++
#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <functional>
using namespace std;
int main()
{
random_device rnd_device;
mt19937 mersenne_engine {rnd_device()};
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);
for (auto i : vec) {
cout << i << " ";
}
}
Example 2: select one random element of a vector in c++
vector<int> v{10,21,24,13};
int random = rand() % v.size();
int sel_elem = v[random];
cout<<"Selected Element: "<<sel_elem<<endl;