【问题标题】:Implementing std::equal with tr1::shared_ptr types用 tr1::shared_ptr 类型实现 std::equal
【发布时间】:2012-10-30 22:37:39
【问题描述】:

无法轻易在网上找到解决方案...

我有类似下面的东西。

class Color {
  public:
    Color(std::string n) : name(n) {}
    typedef std::tr1::shared_ptr<Color> Ptr;
    std::string name;
 };

与此同时……

void Function()
{
    std::vector<Color::Ptr> myVector;
    Color::Ptr p1 = Color::Ptr(new Color("BLUE") );
    Color::Ptr p2 = Color::Ptr(new Color("BLUE") );

    // Note: p2 not added.
    myVector.push_back( p1 );

    // This is where my predicament comes in..
    std::find( myVector.begin(), myVector.end(), p2 );
}

我将如何编写它以便我的 std::find 实际上尊重 smart_pointers 并比较对象字符串而不是它们的内存地址?我的第一种方法是编写一个自定义的 std::equal 函数,但是它不接受模板作为自己的模板类型。

【问题讨论】:

    标签: c++ stl shared-ptr tr1


    【解决方案1】:

    最简单的可能是使用find_if

    template <typename T>
    struct shared_ptr_finder
    {
        T const & t;
    
        shared_ptr_finder(T const & t_) : t(t_) { }
    
        bool operator()(std::tr1::shared_ptr<T> const & p)
        {
            return *p == t;
        }
    };
    
    template <typename T>
    shared_ptr_finder<T> find_shared(std::tr1::shared_ptr<T> const & p)
    {
        return shared_ptr_finder<T>(*p);
    }
    
    #include <algorithm>
    
    typedef std::vector< std::tr1::shared_ptr<Color> >::iterator it_type;
    it_type it1 = std::find_if(myVector.begin(), myVector.end(), find_shared(p2));
    it_type it2 = std::find_if(myVector.begin(), myVector.end(), shared_ptr_finder<Color>(*p2));
    

    【讨论】:

      【解决方案2】:

      你可以实现:

      bool operator==(Color::Ptr const & a, Color::Ptr const & b);
      

      或者,您可以使用 std::find_if 并实现一个谓词,该谓词可以按照您的意愿运行。

      在 C++11 中,它可能看起来像:

      std::find_if( myVector.begin(), myVector.end(), [&](Color::Ptr & x) { return *p2 == *x });
      

      【讨论】:

      • 如果 OP 使用的是 TR1,她可能没有 C++11。
      • @KerrekSB:我同意。但是,将该 lambda 转换为仿函数并不难。
      猜你喜欢
      • 2012-03-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 2012-06-11
      • 2011-08-01
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      相关资源
      最近更新 更多