I know that std::set does not allow non-const access to it's items. I know that it's impossible to move items out of a the set – because any sort of non-const access might break the ordering of the set.
However, we CAN erase an item from the set. This doesn't break it, because it just forces the set to restructure. How come then, we can't 'pop' an item? Why can't I get out the item and erase it at the same time?
The reason I'm asking is - I need an ordered container of unique_ptrs. Occasionally I need to 'pop' unique_ptrs from one container and transfer it them to another. They must be ordered be a custom functor that I've made.
I don't see why a pop functionality shouldn't be allowed?
To extract a node from std::set
you can use extract(...)
member function, that was introduced in C++17:
#include <set>
#include <iostream>
int main()
{
std::set<int> set{1, 5, 3, 7, 2};
std::cout << "Original set: ";
for (auto e : set)
std::cout << e << ' ';
std::cout << '\n';
auto first = set.extract(set.begin());
std::cout << "Extracted value: " << first.value() << '\n';
std::cout << "New set: ";
for (auto e : set)
std::cout << e << ' ';
std::cout << '\n';
}
Output:
Original set: 1 2 3 5 7
Extracted value: 1
New set: 2 3 5 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With