n.caillou n.caillou - 2 months ago 24
C++ Question

c++11, salvaging a set

Is there a clean way of moving the elements of a set out of it ? Something like:

set<A> s {...};
vector<A> v;
for (const A& a : s)
v.push_back(move(const_cast<A&>(a)));
s.clean(); //undefined behavior?

Answer

In C++11, no. The move you're doing is undefined behavior.

In C++17, yes, with extract():

for (auto it = s.begin(); it != s.end(); ) {
    v.push_back(std::move(s.extract(it++)).value()));
}
s.clear();
Comments