To retrieve a random item from a set in C++, you can utilize the `std::vector` container along with the `std::random_device` and `std::uniform_int_distribution` classes.
In this example,
#include <iostream>
#include <vector>
#include <random>
#include <ctime>
int main() {
// Create and populate the set (vector)
std::vector<int> my_set = {1, 2, 3, 4, 5};
// Seed the random number generator
std::random_device rd;
std::mt19937 gen(rd());
// Generate random index
std::uniform_int_distribution<> dis(0, my_set.size() - 1);
int random_index = dis(gen);
// Get random item from set
int random_item = my_set[random_index];
// Print random item
std::cout << "Random item from set: " << random_item << std::endl;
return 0;
}
Random item from set: [random value]
In this tutorial, we learned How to get a Random Item in a Set in C++ language with well detailed examples.