0

I want to declare set of std::unique_ptr<A> like this:

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;

So, what to use in something? The obvious way is to declare a class for comparing two std::unique_ptr<A> by value of A and use it in above container declaration. However is there a better way? May be something predefined exists already? Surely, the problem is pretty standard.

Update: I know there is a question "Order of elements in set of pointers", but this is not what I am asking here. I know how set of pointers works. And I know about the solution, suggested there, which is mentioned in my question. I explicitly asked whether solution without custom-defined class for comparison is possible. E.g. through use of lambda functions?

one_two_three
  • 501
  • 2
  • 10
  • The top/accepted answer in the linked duplicate shows how to order your set, in a pretty succinct way. – Adrian Mole Sep 27 '21 at 13:37
  • The question is about whether I can use *standard* ways for resolving this, surely common, problem, instead of declaring my own special class for comparison. – one_two_three Sep 27 '21 at 13:49
  • Yes, you can do it using a lambda the same way you pass a comparison to something like `std::sort`. You can see an example of that in [this answer](https://stackoverflow.com/a/16895019/12334309), but you'd pass the lambda to the `set` constructor instead of the `sort` function call. – Nathan Pierson Sep 27 '21 at 13:59
  • Actually, I suppose it's not quite as simple as passing it to `sort` because the relevant constructor is such that CTAD won't kick in. It's still possible to do this with a lambda instead of a full-on comparator class with a decltype, see [here](https://godbolt.org/z/jo67MPfG7) for an example. _Use caution with this_ because if you change the value of the `weight` of an `A` contained in this set you'll get undefined behavior. – Nathan Pierson Sep 27 '21 at 14:18
  • "A better way" is a matter of opinion. To avoid, the question should include requirements and a statement of why providing a `Compare` template argument doesn't satisfy the requirements. Also, remove/rewrite the `/*something*/` line, as "Order of elements in set of pointers" provides the answer for that form. – outis Sep 30 '21 at 20:25

0 Answers0