How to get a random element from a C++ container?

Viewed 80901

What is a good way to get a [pseudo-]random element from an STL range?

The best I can come up with is to do std::random_shuffle(c.begin(), c.end()) and then take my random element from c.begin().

However, I might want a random element from a const container, or I might not want the cost of a full shuffle.

Is there a better way?

9 Answers
#include <vector>
using std::vector;

vector<int> vi = {1, 2, 3, 4, 5};
srand(time(0));
randomPosition = rand() % vi.size();
randomElement = vi[randomPosition]

srand(time(0)) seed for random, if not use it, it will get same random integer every execution.

Related