Equivalent to python set.pop () for C ++ unordered sets

Does C ++ have the python equivalent of set.pop() ? I looked at the documentation for unordered_set here , but there seems to be no way: 1. Access an arbitrary element, and / or 2. Access + delete an arbitrary element (popping).

+6
source share
3 answers

Note that the C ++ standard library is intentionally designed so that the various specifications of the container do not include the β€œget and delete” function: for example. for vector , you have back() , which returns the value at the end, and you have pop_back() , which removes the value at the end, but does not return it.

The reasons for this may be the content of a separate issue.

What you really want is a method to get the element (e.g. begin() , as suggested in the comments) and then delete it as soon as you receive it (e.g. erase(iterator) , as indicated in another answer).

+2
source

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).

+7
source
0
source

Source: https://habr.com/ru/post/975618/


All Articles