I created this template function to find and delete and item from collection of shared_ptr
template<class T>
bool FindAndDelete(set<shared_ptr<T>>& collection, shared_ptr<T> item)
{
auto foundItem = find(collection.begin(), collection.end(), item);
if(foundItem != collection.end())
{
collection.erase(foundItem);
return true;
}
else
{
return false;
}
}
Question:
How could I generalize it more to cover all collections? (vector, list, etc…)
for example
template<class K, class T>
bool FindAndDelete(K<shared_ptr<T>>& collection, shared_ptr<T> item);
Note: I come from C#, so maybe the code is a bit off 🙂 Correct me please
If you want to remove elements from a container, then something like this would work:
Bear in mind that the
value_typeof maps is anstd::pair<key_type, mapped_type>, so you may want to provide special versions for those, for exampleand similarly for
std::multimapand C++11std::unordered_*variants. These containers havefindmember functions that are more efficient thanstd::find, so it would be worthwhile to have dedicated implementations offindAndDeleteto take advantage of this.You could also have a look at std::remove_if and the erase remove idiom as an alternative to your implementation for non-associative containers. This could be more efficient in the case where you have duplicates.