Can I use operator == for pointers?

I created some object with an overloaded == operator in it.

class Corridor { public: Corridor(int iStart, int iEnd); ~Corridor(); // Overloaded operators to simplify search in container. friend bool operator==(const Corridor& lhs, const int rhs); friend bool operator==(const int lhs, const Corridor& rhs); protected: int m_iIntersectionIDStart; int m_iIntersectionIDEnd; }; 

In this case, if I create the Corridors vector somewhere:

  vector<Corridor> m_vCorridors; 

proggram works fine and I can use the search algorithm:

  auto itCorridor = find(m_vCorridors.begin(), m_vCorridors.end(), someID); 

BUT in case I create a vector of pointers:

  vector<Corridor*> m_vCorridors; 

I get errors: Error 1 error C2446: '==': there is no conversion from 'const int' to 'Corridor *' c: \ program files (x86) \ microsoft visual studio 10.0 \ vc \ include \ algorithm 41 Error 2 errors C2040 : '==': "Corridor *" differs in indirection from "const int" c: \ program files (x86) \ microsoft visual studio 10.0 \ vc \ include \ algorithm 41

Tried to overload operator == in different ways, but in this case it does not work. Does anyone know what I should do to solve the problem?

+4
source share
1 answer

This is because find tries to compare a pointer to a Corridor with an int . To compare Corridor with int again, you will need to define your own comparator using find_if . Assuming you can use lambdas C ++ 11,

 find_if(m_vCorridors.begin(), m_vCorridors.end(), [=](Corridor* cp) { return *cp == someID; }); 
+9
source

Source: https://habr.com/ru/post/1486278/


All Articles