Reputation: 31
Dear Experts, I have a vector named Dstr and If I do Dstr.size() it gives me an array. I want to choose a candidate from that Dstr/Dstr.size() randomly. Could you please suggest me how to do that in c++ ?
Thanks in advance Regards
Upvotes: 0
Views: 117
Reputation: 625
Here's the C++ way of generating a random number. I am assuming that your array/vector is not empty
size_t random(size_t min, size_t max)
{
static std::mt19937 randGen( std::random_device{}() );
return std::uniform_int_distribution<size_t>(min, max)(randGen);
}
auto val = Dstr.at(random(0, Dstr.size() - 1));
Upvotes: 1
Reputation: 26272
To get a random element out of your vector, you can use std::sample
:
decltype(Dstr)::value_type element;
std::sample(Dstr.begin(), Dstr.end(), &element, 1, std::mt19937{std::random_device{}()});
C++17 is required.
Upvotes: 3
Reputation: 910
auto candidate = Dstr[rand() % Dstr.size()];
Upvotes: -1