Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...