首页 > 解决方案 > 如果我希望它按对象而不是指针排序,那么声明一组 std::unique_ptr 的好方法?

问题描述

我想声明这样的集合std::unique_ptr<A>

class A
{
public:
  ///type of itself
  typedef A self;

  ///Simple constructor
  A(int w) : weight(w) {}

  ///To use for sorting
  bool operator<(const self& another)
  { 
    return weight < another.weight;
  }
private:
  int weight;
};//class A

//Container of pointers to A sorted by object, not by pointer values.
std::set(std::unique_ptr<A>, /*something*/) storage_for_A;

那么,在某事中使用什么?显而易见的方法是声明一个用于比较两个std::unique_ptr<A>值的类,A并在上面的容器声明中使用它。然而有没有更好的方法?可能已经存在预定义的东西?当然,这个问题很标准。

更新:我知道有一个问题“指针集中元素的顺序”,但这不是我在这里要问的。我知道指针集是如何工作的。而且我知道那里建议的解决方案,这在我的问题中提到了。我明确询问是否可以使用没有自定义类进行比较的解决方案。例如通过使用 lambda 函数?

标签: c++lambdasetunique-ptr

解决方案


推荐阅读