Dev
Dev

Reputation: 21

std::set with custom comparator operator on object at compile time

I have a class (Namely A) which contains std::set as member variable. Now I want create 2 objects of class A such that:

 class A {
     std::set<int, <magic custom operator>>; 
 };

A obj1 - Ascending order
A obj2 - Descending order

How can I achieve this functionality at compile(run) time, so that the set will hold the objects in ascending or descending order based on the object.

Any help on this is very much appreciated.

Upvotes: 0

Views: 140

Answers (1)

Marshall Clow
Marshall Clow

Reputation: 16670

Your comparator can have state. For example,

struct StatefulComparator {
   StatefulComparator(bool b) : ascending_(b) {}
   bool operator()(int lhs, int rhs) const {
      return ascending_
          ? lhs < rhs
          : lhs > rhs;
   }
   bool ascending_;
};

Then pass the comparator to the set constructor:

std::set<int, StatefulComparator> ascendingSet (StatefulComparator(true));

Upvotes: 2

Related Questions