0

I'm trying to modify a functor to accept an argument so I could sort a set based in that parameter. I just can't figure it out

struct sortset {
  bool operator() (const string& s1, const string& s2) const {
    //Sorting algorithm depending on "sortingVar"
  }
};

main() {
  string sortingVar; cin >> sortingVar;
  set<string, sortset> mySet;
  ...
}
Joan Pastor
  • 51
  • 1
  • 7

1 Answers1

1

Give the comparator a constructor which accepts the argument to determine the comparator's behaviour:

struct sortset
{
  sortset(const string& sortingVar) : sortingVar(sortingVar) {}

  bool operator() (const string& s1, const string& s2) const {
    //Sorting algorithm based on "sortingVar"
  }
private:
  const string sortingVar;
};

int main() {
  string sortingVar; cin >> sortingVar;

  // Either:
  set<string, sortset> mySet{sortset{sortingVar}};

  // Or:
  sortset comp{sortingVar};
  set<string, sortset> mySet{comp};

  // ...
}

Notice that the set constructor allows you to provide an actual instance of the comparator, so you can use that to pass one that is not default-constructed (a good thing too, since no such thing can now exist).

Add some std::moves if you like.

Don't forget to give main a return type.

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989