5

std::shared_ptr のコンテナーがあります。std::equal を使用して 2 つのコンテナーを比較したいと考えています。クラス A には operator== が定義されています。各要素が、shared_ptr で定義されたものではなく、operator== を使用して同等であるかどうかを比較したい。

equal に渡す関数または関数オブジェクトを作成する必要がありますか? それとも、より単純なビルトインがありますか (<functional> で定義されているものなど)?

4

3 に答える 3

7

関数、関数オブジェクト、またはラムダ式が必要になります ( を使用できるためstd::shared_ptr、C++0x の一部が既に有効になっています)。

あなたを助けるものは何もありませんが<functional>、ブーストには何かがあります:間接イテレータ

#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
#include <boost/iterator/indirect_iterator.hpp>
int main()
{
        std::vector<std::shared_ptr<int>> v1;
        std::vector<std::shared_ptr<int>> v2;
        v1.emplace_back( new int(1) );
        v2.emplace_back( new int(1) );

        bool result =
            std::equal( boost::make_indirect_iterator(v1.begin()),
                        boost::make_indirect_iterator(v1.end()),
                        boost::make_indirect_iterator(v2.begin()));
        std::cout << std::boolalpha << result << '\n';
}
于 2011-03-31T19:00:05.813 に答える
6

ラムダをサポートするコンパイラがあり、アイテムがnullになることはないと仮定すると、次のようなことができます。

bool CompareA(const vector<shared_ptr<A>>& first, 
              const vector<shared_ptr<A>>& second) {

   return equal(first.begin(), first.end(), second.begin(),
              [](const shared_ptr<A>& item1, const shared_ptr<A>& item2) -> bool{
                   return (*item1 == *item2);
               });
}
于 2011-03-31T18:57:57.200 に答える
0

個人的には、関数オブジェクトが最善の策だと考えています...私が見たものはすべて<functional>、正しい比較型を持つことに依存しています。つまり、ポインター自体を比較したくない場合は、どういうわけか、それらが指しているオブジェクトへのポインターの逆参照が必要です... STLには、その逆参照を自動的に行うヘルパーはありません。

ありがとう、

ジェイソン

于 2011-03-31T19:01:43.287 に答える