Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move `unique_ptr`s between sets

I have two sets and an iterator to an element of a:

set<unique_ptr<X>> a, b;
set<unique_ptr<X>>::iterator iter = find something in a;

I would like to remove the element pointed by iter from a and insert it into b. Is it possible? How?

like image 913
Yakov Galka Avatar asked May 05 '15 09:05

Yakov Galka


1 Answers

Well, I suspect there is no normal way to do it. But there is always a non-normal one :) You can do the following:

auto tmp = const_cast<std::unique_ptr<std::string>&&>(*iter);
a.erase(iter);
b.insert(std::move(tmp));

Ok, the very first line violated set invariant and it is horrible but as far as I understand it should not be a problem since on the very next line we remove this evil node from the set.

like image 111
ixSci Avatar answered Sep 19 '22 13:09

ixSci