如何选择一个随机元素std::set?
我天真地试过这个:
int GetSample(const std::set<int>& s) {
double r = rand() % s.size();
return *(s.begin() + r); // compile error
}
Run Code Online (Sandbox Code Playgroud)
但这operator+是不允许的.
xto*_*ofl 44
你可以使用这个std::advance方法.
#include <set>
#include <algorithm>
int main() {
using namespace std;
// generate a set...
set<int> s;
for( int i = 0; i != 10; ++i ) s.insert(i);
auto r = rand() % s.size(); // not _really_ random
auto n = *select_random(s, r);
}
Run Code Online (Sandbox Code Playgroud)