在shared_ptr的容器上使用C ++ std :: equal

时间:2011-03-31 18:49:39

标签: c++ shared-ptr equality stl-algorithm

我有一个std :: shared_ptr的容器。我想使用std :: equal来比较两个容器。 A类有operator == defined。我希望等于比较每个元素是否等效使用其运算符==,而不是在shared_ptr中定义的那个。

我是否需要将函数或函数对象传递给相等的?或者是否有一些更简单的东西(比如在< functional>中定义的东西)?

3 个答案:

答案 0 :(得分:7)

您将需要一个函数或函数对象或lambda表达式(因为您可以使用std::shared_ptr,您已经启用了C ++ 0x的某些部分。)

<functional>中没有任何内容可以帮助您,但有一些内容可以提升:indirect iterator

#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';
}

答案 1 :(得分:3)

你可以做类似下面的事情,假设你有一个支持lambdas的编译器,并且没有任何项永远为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);
               });
}

答案 2 :(得分:0)

我个人认为功能对象是最好的选择......我在<functional>看到的所有东西都取决于拥有正确的比较类型,这意味着如果你不想要比较指针本身,你会以某种方式需要取消引用那些指向他们指向的对象的指针...我没有在STL中看到任何自动为你做引用的帮助。

谢谢,

杰森