I have a std::set of unique pointers in a class like std::set<std::unique_ptr<T>> my_set{};
, and I want to write a method that produces a sorted vector of the values pointed to by these unique pointers.
Currently I've got:
auto convert() -> std::vector<T> {
auto vec = std::vector<T>();
for (auto const& element : my_set) {
vec.push_back(element.get());
}
return vec;
}
However, I'm not sure this will produce the required sorting that I want? Would anyone know how I can sort the pointers in the set such that the values pointed to are in increasing order (meaning I can just push each one back onto the set)?
EDIT: to do the question can I use std::transform(my_set.begin(), my_set.end(), vec.begin(), [](std::unique_ptr<T> ptr) -> T { return ptr.get(); });
?
The set is sorted by the pointer value, not by the values; so you need to sort the result after (note that there may be duplicates because the pointers are to unique instances, but the values pointed to may be equivalent for the order relation on T
).
I actually find this design quite confusing... if you care about identity (so you have unique pointers) how is possible that it's ok to use an std::vector<T>
that is a container of values (i.e. identity doesn't matter)?