在STL上操作的generalize函数设置为所有集合

miz*_*_sk 3 c++ stl c++11

我创建了这个模板函数来查找和删除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;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:我怎样才能更多地概括它以涵盖所有收藏?(矢量,列表等......)

例如

template<class K, class T>
bool FindAndDelete(K<shared_ptr<T>>& collection, shared_ptr<T> item);
Run Code Online (Sandbox Code Playgroud)

注意:我来自C#,所以也许代码有点关闭:)请纠正我

jua*_*nza 6

如果你想从容器中删除元素,那么这样的东西可以工作:

template<class K>
bool FindAndDelete(K& collection, typename K::value_type item);
Run Code Online (Sandbox Code Playgroud)

请记住,value_type地图是一个std::pair<key_type, mapped_type>,因此您可能希望为这些地图提供特殊版本

template<typename T, typename K>
bool FindAndDelete(std::map<T,K>K& collection, 
                   typename std::map::<T,K>::key_type key);
Run Code Online (Sandbox Code Playgroud)

std::multimapC++ 11 std::unordered_*变体类似.这些容器具有findstd::find其更高效的成员函数,因此值得专门实现findAndDelete以利用此功能.

您还可以查看std :: remove_iferase remove惯用法,作为非关联容器实现的替代方法.如果您有重复项,这可能会更有效.