Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use operator== for pointers?

I created some Object with 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 somewhere vector of Corridors:

    vector<Corridor> m_vCorridors;

proggram works fine and I'm able to use find algorithm:

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

BUT in case if I create vector of pointers:

    vector<Corridor*> m_vCorridors;

I receive an errors: Error 1 error C2446: '==' : no conversion from 'const int' to 'Corridor *' c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm 41 Error 2 error C2040: '==' : 'Corridor *' differs in levels of 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 it doesn't work for this case. Does somebody knows what I should do to resolve issue?

like image 730
SunFlower Avatar asked Jan 13 '23 03:01

SunFlower


1 Answers

That's because find is attempting to compare a pointer to a Corridor to an int. To compare the Corridor to the int again, you would need to define your own comparator, using find_if. Assuming you can use C++11 lambdas,

find_if(m_vCorridors.begin(), m_vCorridors.end(), [=](Corridor* cp) {
    return *cp == someID;
});
like image 177
Matt Kline Avatar answered Jan 21 '23 20:01

Matt Kline