PetrS
PetrS

Reputation: 1110

C++ Overload operator ==

I have created a class Location. This class is a parent class for classes City and Village. The Location class is abstract. I have created a vector<Location*> locations, which contains cities and villages. Location contains a name. If two locations have the same name, it means that they are same. I have overloaded operator == for Location.

bool operator==(const Location& lhs) const
{
    return (this->mName.compare(lhs.mName) == 0);
}

If I want to add some location into the vector, I firstly check if this location does not exist. I use this function:

bool checkLocation(Location* l) {
    return find(locations.begin(), locations.end(), l) != locations.end();
}

For example, if I want to add some city into the vector, the method above still returns false, which means, that Location does not exist. But in the vector there is a city with same name. Can you tell me please, where is the problem? Thank you.

Upvotes: 1

Views: 116

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361322

Since your vector stores pointers, std::find will compare the pointers, which will not invoke Location::operator==() to compare the elements.

You need to use std::find_if along with lambda:

return std::find_if(locations.begin(), 
                    locations.end(), 
                    [l](Location  const *x) {
                         return *l == *x;      //invoke operator=
                     }) != locations.end();

The lambda dereferences the pointers, and then uses == invoke the Location::operator=.

If the location objects are not huge, I would advise you to use std::vector<Location> instead of std::vector<Location*>. If you use std::vector<Location>, then you can use std::find and the code will be simplied.

Even if location objects are huge, it is better to use smart pointer instead of raw pointer.

Hope that helps.

Upvotes: 7

Rakib
Rakib

Reputation: 7625

You are storing Location* in the vector. The find algorithm will compare the values of the pointer, not the name in the Location object. You have to provide custom comparer to the algorithm.

Upvotes: 1

Related Questions