You can put the first element
auto i = *set.begin(); set.erase(set.begin());
or if you are overly concerned about the internal bucket ordering defined by the implementation (hint: you probably shouldn't be), you can remove the random element with something like
#include <unordered_set> #include <iostream> #include <random> int main() { std::unordered_set<int> set{0, 1, 2, 3, 4, 5}; std::default_random_engine ran{std::random_device{}()}; auto it = set.begin(); std::advance(it, std::uniform_int_distribution<>{0, set.size() - 1}(ran)); std::cout << *it << '\n'; set.erase(it); }
The above is not particularly efficient, and you might be better off filling out std::vector , removing duplicates, randomizing the order, and then just pop_back elements.
#include <algorithm> #include <vector> #include <iostream> #include <random> int main() { std::vector<int> vec{0, 1, 2, 3, 3, 4, 5, 5}; std::sort(vec.begin(), vec.end()); vec.erase(std::unique(vec.begin(), vec.end()), vec.end()); std::shuffle( vec.begin(), vec.end(), std::default_random_engine{std::random_device{}()} ); while (!vec.empty()) { std::cout << vec.back() << '\n'; vec.pop_back(); } }
(nb depending on your platform random_device may not be a very good seed).