3

このテンプレート関数を作成して、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;
    }
}

質問: すべてのコレクションをカバーするために、どのように一般化できますか? (ベクトル、リストなど...)

例えば

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

注: 私は C# 出身なので、コードが少しずれている可能性があります :) 訂正してください

4

2 に答える 2

6

コンテナから要素を削除したい場合は、次のようになります。

template<class K>
bool FindAndDelete(K& collection, typename K::value_type item);

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);

同様に forstd::multimapおよび C++11std::unordered_*バリアント。これらのコンテナにfindは よりも効率的なメンバー関数がstd::findあるため、これを利用するために を専用に実装する価値がありfindAndDeleteます。

非連想コンテナの実装の代替として、std::remove_iferase remove イディオムを確認することもできます。重複がある場合、これはより効率的です。

于 2012-11-26T09:00:51.077 に答える
1
template <template<typename> class K, typename T>
bool FindAndDelete(K<shared_ptr<T> > &collection, shared_ptr<T> item);
于 2012-11-26T09:00:02.510 に答える