Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

c++14 - How to make a comparator function inside any class just like we make in a priority_queue in c++ STL

Just like in a priority_queue in STL we can give our custom compare function like this:

class comp
{
    bool operator()(int a, int b)
    {
        return a>b? 1:0;
    }
};
priority_queue<int, vector<int>, comp> pq;

How can I do this for any class? I tried doing this to compare my person class object using class c:

class person
{
  public:
  int height;
  int age;
  person(int a, int h)
  { 
     age = a;
     height = h;
  }
};

template<class comparator>
class c
{
   public:
   vector<person>p;
   void compare(person p1, person p2)
   {
     if(comparator comp( p1,  p2))
     {
      p.push_back(p1);
     }
   }
};

class compare
{
    bool operator()(person p1, person p2)
    {
        return p1.height> p2.height ? 1:0;
    }
};

and then I created 2 person objects and a class c object "pq", then called the compare function like we do in priority_queue:

person p1(23, 85);
person p2(11, 55);
c <compare> pq;
pq.compare(p1, p2);

but it is giving this error.

    error: expected primary-expression before 'comp'
             if(comparator comp(p1, p2))
                           ^~~~

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to create an instance of the functor you want to compare with, and then call that instance's operator().

This:

if(comparator comp( p1,  p2))

does not do that. You seems to be trying to just construct a comparator called comp in the if condition - which can't be done - and made no effort actually to call said comparator anyway. Change that to this:

   void compare(person p1, person p2)
   {
     if (comparator{}(p1, p2)) // fixed
     {
       p.push_back(p1);
     }
   }

i.e. first constructing a comparator with {} and then calling the operator() thereof with ().

That means you need its operator() to be accessible outwith itself:

class compare
{
public: // added (or omit this and change class to struct)
    bool operator()(person p1, person p2)
    {
        return p1.height> p2.height ? 1:0;
    }
};

With these changes, it compiles fine. I didn't check whether it does what you want, but you obviously need to fix these syntax errors first.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...