Scenario
I’ve run into a speedbump while using the STL with what seems like a normal scenario, simplified here:
class Person {
string Name;
int Age;
};
vector<Person> people;
AddPeople(people);
string s("Bob");
find(people.begin(), people.end(), s);
Problem
Unfortunately find
wants to compare the entire class.
Question
Is there a better or more appropriate way to do this the “STL way”? The suggested questions weren’t helpful, but I managed to find a couple of related questions but no direct solution.
Work-arounds/Tests
There’s some potential work-arounds:
Forgo
find
altogether (cluttered, but could be refactored):bool bBob = false; for (UINT i = 0; i < people.size(); i++) { if (people[i].Name == s) bBob = true; break; }
Provide conversion operator (implicit conversion doesn’t work; explicit can’t be used in
find
):class Person { string Name; int Age; operator string() {return Name;} };
Person b ("Bob", 99); string s ("Bob"); b == s; //doesn’t work string(b) == s; //works, but no good for find()
Define a standalone equality operator (simple, effective, but globally exposed):
BOOL operator==(Person l, string r) { return l.Name == r; }
Define a member equality operator (makes comparison order dependent; object must be first):
class Person { string Name; int Age; bool operator==(string s) {return Name == s;} };
Person b ("Bob", 99); string s ("Bob"); b==s; //works s==b; //doesn’t work, but not a problem for find()
It looks like #4 is the best candidate, but none seem ideal or feel “STL”, and some have problems.
See Question&Answers more detail:os