Is there a way to delete from a set and move the value to a temporary?

Viewed 63

Is there a way to delete an item in a set / map and get the former value as a temporary return value so that I can move() somewhere else ?

1 Answers

Yes, use .extract().

#include <iostream>
#include <memory>
#include <set>


int main()
{
    using elem = std::unique_ptr<int>;

    std::set<elem> set;
    set.insert(std::make_unique<int>(1));
    set.insert(std::make_unique<int>(2));
    set.insert(std::make_unique<int>(3));

    // auto iter = set.find(...);
    auto iter = set.begin(); // Some iterator.

    elem x = std::move(set.extract(iter).value());

    std::cout << *x << "\n\n"; // 1
    for (const auto &it : set)
        std::cout << *it << '\n'; // 2 3
}

I'm using non-copyable std::unique_ptr<int> as the element type to demonstrate that no copies are being made.

Related