1

I'm learning vectors and now I've got a problem: binary ==: no operator found which takes a left hand operand of type 'Object'. I've found out that there is no mustake after deleting:

vector<Object>::iterator it = find(list.begin(), list.end(), name);

And I don't know what to do. Maybe you will ask something like this

class Object {
private:
    string* name;
    vector<string>* facts;
public:
//...
}
    class ListOfObjects {
private:
    vector<Object> list;
public:
    void Realise(string* knowledge);
};

void ListOfObjects::Realise(string* knowledge) {
    //...
    vector<Object>::iterator it = find(list.begin(), list.end(), name);
    //...
}
ettudagny
  • 95
  • 1
  • 2
  • 12
  • 1
    [Operator overloading](http://stackoverflow.com/questions/4421706/operator-overloading), especially `operator==`. – Deduplicator Jan 10 '16 at 17:49
  • 1
    `name` is a `std::string*` and you're trying to look for it in a vector of `Object`. You need to define a suitable equality operator for `Object`. You also probably shouldn't use pointers to `std::string` – it's very rarely useful. – molbdnilo Jan 10 '16 at 17:49
  • `std::string*` What's the issue with just using `std::string`, or `vector facts`? And you shouldn't really name your variable as `list`. – PaulMcKenzie Jan 10 '16 at 17:51

2 Answers2

1

The problem is given by the fact that std::find utilizes operator== to check if the element you are searching is present in the current selection.

Since you pass a string* then the method searched when compiling the std::find template method is

bool Object::operator==(string* argument) const

which must be implemented, and its implementation would be something like

bool Object::operator==(string* argument) const
{
  return *argument == name;
}

But I see potential issues with this solution:

  • you are searching for element in a collection through a specific field, if this is the predominant way you are using, then another different collection would be better, eg std::unordered_map<string, vector<string>>, which would make everything easier
  • you are allowed to overload operator== with an argument of a type different from the type you are overloading the operator for, while this works and it can be used it doesn't make much sense in terms of equality since you are comparing two different types
  • you are working with string* which doesn't make sense most of the time (pass const std::string& if you want to avoid copies)
Jack
  • 131,802
  • 30
  • 241
  • 343
0

I think what you'd be looking for if you want to compare objects in that way would be called operator overloading. Here is a short example:

http://www.learncpp.com/cpp-tutorial/94-overloading-the-comparison-operators/

Take note of how operator== is used