Souvik Maity
Souvik Maity

Reputation: 31

How to choose a number randomly from a list/Array in c++?

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

Answers (3)

Midnight Exigent
Midnight Exigent

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

Evg
Evg

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

auto candidate = Dstr[rand() % Dstr.size()];

Upvotes: -1

Related Questions