Question

I have the following comparator for string objects

struct Comparator{

  int x;

  bool operator() (string a, string b) {

    int i = 1;

    if(a < b) {
      i = -1;
    } 

    i*= x;

    if(i==-1) {
      return true;
    } 

    return false;

  }

};

As you can see, it has a parameter x. when it is = 1 the comparison of strings is normal and when it is =-1 the comparison is inverted.

When using it in a method like sort for vector elements I can give the object instance of this comparator with the right x, but when I want to give this comparator to a template class like set, I need to give a class and not an object instance. So the only solution I see is to make x static. Is there a better solution?

Here is the example of a main where I would like to use this comparator:

int main(int argc, char** argv)
{

  vector<string> vec;

  vec.push_back("c");
  vec.push_back("a");
  vec.push_back("b");

  Comparator comp;

  comp.x = 1; // for normal comparison
  comp.x = -1; // for inverse comparison

  sort(vec.begin(),vec.end(), comp); // here I can give the functor instance

  for(vector<string>::iterator it = vec.begin() ; it != vec.end(); it++)
  {
    cout << *it << endl;
  }

  set<string, Comparator> ss; // but here I must give the name of the functor class

  ss.insert("c");
  ss.insert("a");
  ss.insert("b");

  for(set<string>::iterator it = ss.begin() ; it != ss.end(); it++)
  {
    cout << *it << endl;
  }

  return 0;
}
Was it helpful?

Solution

All the relevant constructors of set also take an instance of Comp class.

 set<string, Comparator> ss(Comparator(-1)); 

Now you only need a constructor for Comparator that initializes its member x with an appropriate value.

That said, the standard library already comes with a comparator class for this purpose:

set<string, std::greater<std::string> > ss;

OTHER TIPS

That will not work: a < b does not(!) mean b < a.

You might utilize std::string::compare:

bool operator() (const std::string& a, const std::string& b) {
    int result = a.compare(b) * x;
    return result < 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top