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:
template<class K>
bool FindAndDelete(K& collection, typename K::value_type item);
Bear in mind that the value_type of maps is an std::pair<key_type, mapped_type>, so you may want to provide special versions for those, for example
template<typename T, typename K>
bool FindAndDelete(std::map<T,K>K& collection,
typename std::map::<T,K>::key_type key);
and similarly for std::multimap and C++11 std::unordered_* variants. These containers have find member functions that are more efficient than std::find, so it would be worthwhile to have dedicated implementations of findAndDelete to 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With