mercredi 1 décembre 2021

can we define 'operator<' as member function of a class to work with std::less?

I am trying to write member function which can be used when we call std::less. I defined a 'pqueue' class which stores contents in dequeue internally and uses std::less to compare. Defined one more class 'myClass' and I am using pqueue to store objects of the class. Code is as below.

#include <iostream>
#include <deque>
#include <algorithm>
#include <functional>

using namespace std;

template <class T> class PQueue
{

   public:

      PQueue();
      ~PQueue();

      void push(T & item);
      void push(T && item);

      T & front();

      using Queue = std::deque<T>;

   protected:
   
      Queue q_;
};


template <class T> PQueue<T>::PriorityQueue()
{
}

template <class T> PQueue<T>::~PriorityQueue()
{
}

template <class T> void PQueue<T>::push(T & item)
{
   q_.emplace_back(item);
}

template <class T> void PQueue<T>::push(T && item)
{
   q_.emplace_back(item);
}

template <class T> T & PQueue<T>::front()
{
   std::partial_sort(q_.begin(), q_.begin()+1, q_.end(), std::less<T>{});

   return q_.front();
}

class myClass
{
    public:
        myClass(int x)
        {
            y = x;
        }
        
        int y;
        
        friend bool operator < (const myClass &obj1, const myClass &obj2);
        /*bool operator < (const myClass &obj)
        {
            return y < obj.y;
        }*/
};

bool operator < (const myClass &obj1, const myClass &obj2)
{
    return obj1.y < obj2.y;
}

int main()
{
    myClass obj1(10);
    myClass obj2(2);
    myClass obj3(100);
    
    PQueue<myClass> queue;
    queue.push(obj1);
    queue.push(obj2);
    queue.push(obj3);
    
    cout << queue.front().y;
    return 0;
}

Above code is working fine if I define 'operator <' function as friend function of myClass. But if I define the 'operator <' function as member function of myClass as below, it is throwing error.

bool operator < (const myClass &obj)
{
    return y < obj.y;
}

ERROR:

/usr/include/c++/9/bits/stl_function.h:386:20: error: no match for ‘operator<’ (operand types are ‘const myClass’ and ‘const myClass’)
  386 |       { return __x < __y; }
      |                ~~~~^~~~~
main.cpp:79:14: note: candidate: ‘bool myClass::operator<(const myClass&)’ 
   79 |         bool operator < (const myClass &obj)
      |              ^~~~~~~~
main.cpp:79:14: note:   passing ‘const myClass*’ as ‘this’ argument discards qualifiers

As per the error, it is clear that operator< function should take const objects as arguments and it is not possible if we define this function as member function of the class. But as per one of stack overflow answers, we can define this as member function.

how to use overloaded std::less for std::map

Can anyone please let me know if we can define operator< function as member function to use for std::less and if yes, please let me know any errors in the code.

Aucun commentaire:

Enregistrer un commentaire