mizi_sk
mizi_sk

Reputation: 1007

generalize function operating on STL set to all collections

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

Upvotes: 3

Views: 157

Answers (2)

juanchopanza
juanchopanza

Reputation: 227488

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.

Upvotes: 6

tmyklebu
tmyklebu

Reputation: 14215

template <template<typename> class K, typename T>
bool FindAndDelete(K<shared_ptr<T> > &collection, shared_ptr<T> item);

Upvotes: 1

Related Questions