// random.cc
// c++11/c++14/c++17
#include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>
using namespace std;
template<typename Iter, typename RandomGenerator>
Iter select_randomly(Iter start, Iter end, RandomGenerator *g) {
std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);
std::advance(start, dis(*g));
return start;
}
template<typename Iter>
Iter select_randomly(Iter start, Iter end) {
static std::random_device rd;
static std::mt19937 gen(rd());
return select_randomly(start, end, &gen);
}
int main() {
vector<int> vec{0, 1, 2, 3, 4};
for (auto i = 0; i < 10; ++i) {
cout << *select_randomly(vec.begin(), vec.end()) << endl;
}
return 0;
}
网友评论