n.caillou
n.caillou

Reputation: 1342

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.clear(); //undefined behavior?

Upvotes: 1

Views: 63

Answers (1)

Barry
Barry

Reputation: 303337

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();

Upvotes: 5

Related Questions