Reputation: 5339
Here is what a typical vector remove-erase operation looks like :
auto toErase = std::remove_if(vec.begin(), vec.end(),
[val](obj_t const& obj) { return obj.myval == val; }
); // This actually moves objects around !
vec.erase(toErase, vec.end());
This works fine in the majority of cases, but I am faced with the case where obj_t
type does not allow move or copy semantics. Objects are inserted with vec.emplace_back()
, and I am looking for an alternative to remove_if
that doesn't need either copy or move.
Does it already exist somewhere ? If not, how would it be built ?
Upvotes: 0
Views: 938
Reputation: 1293
It is not possible to remove from std::vector
without copy or move support: how will you handle case, when you delete something from the middle? You can use for example std::list<Class>
or std::vector<std::shared_ptr<Class>>
instead of std::vector<Class>
.
Actually, if the main problem around remove_if
: I recommend you use shared_ptr
or unique_ptr
Upvotes: 3
Reputation: 4713
If object is non-movable/copyable how do you expect to rearrange objects in the vector? Vector is a contiguous container - so you cannot erase an element in the middle without shifting the ending.
To resolve the issue, either make the object movable/copyable, wrap it in unique_ptr
(thus making it movable), or use one of map/set/unordered_map
containers as those don't relocate objects unlike std::vector
Upvotes: 5