0

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

  • One should hold integers in ascending order (odd numbers)
  • other should hold integers in descending order (even numbers)
 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.

cigien
  • 57,834
  • 11
  • 73
  • 112
Dev
  • 21
  • 3
  • 3
    Does this answer your question? [Using custom std::set comparator](https://stackoverflow.com/questions/2620862/using-custom-stdset-comparator) – cigien Oct 21 '20 at 16:23
  • 1
    The question aims more on having two objects with different sorting, right? I guess OP knows how to use a comparator in general. – Lukas-T Oct 21 '20 at 16:32
  • @cigien Not really: OP knows how that you can use a custom comparator, but not how you can have two of the same type that do different things. It's not a big step to get there, but... – HTNW Oct 21 '20 at 16:33
  • @churill I concur, though it is also exemplary of the world we live in where one knows how to specify custom comparators for standard library containers, whilst simultaneously navigating in fog when discerning the *difference* between compile-time and run-time. – WhozCraig Oct 21 '20 at 16:35
  • 1
    @churill @ HTNW, it's actually not clear that the OP knows how to pass a custom comparator. If the question is edited to add that, then yes, the dupe is incorrect. – cigien Oct 21 '20 at 16:36

1 Answers1

2

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));

Marshall Clow
  • 15,972
  • 2
  • 29
  • 45
  • I tried @Marshall Clow Solution, but it is throwing the linker error. auto add(uint32_t n)-> void { ms(mE).emplace(n); } friend auto operator<<(std::ostream& s, A& fd) -> std::ostream& { for (auto & n : fd.ms(fd.mE)) { s << n << " "; } return s; } bool mE; std::set ms (cmp(mE)); }; "OutFileData::mDataset(StatefulComparator)", referenced from: ns::operator<<(std::__1::basic_ostream >&, ns::OutFileData&) in OutFileData.o – Dev Oct 22 '20 at 10:03
  • Thanks for the quick turnaround. Please take a look at the url(http://cpp.sh/7t54z) and let me know your comments. – Dev Oct 23 '20 at 01:03