在shared_ptr

的容器上使用C ++ std :: equal 我有一个std :: shared_ptr的容器。我想使用std :: equal来比较两个容器。 A类有operator == defined。我希望等于比较每个元素是否等效使用其运算符==,而不是在shared_ptr中定义的元素。 我是否需要使函数或函数对象传递给相等的?或者是否有一些更简单的东西(比如在< functional>中定义的东西)?     
已邀请:
您将需要一个函数或函数对象或lambda表达式(因为您可以使用
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';
}
    
您可以执行以下操作,假设您有一个支持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);
               });
}
    
我个人认为函数对象是最好的选择...我在
<functional>
中看到的所有东西都取决于具有正确的比较类型,这意味着如果你不想比较指针本身,那你就是会以某种方式需要取消引用那些指向他们所指向的对象的指针......我没有在STL中看到任何自动为你取消引用的帮助器。 谢谢, 贾森     

要回复问题请先登录注册