C++ Find object member value in Vector -
i have struct of person contains 2 values - first initial , first name.
there vector of these person structs.
i need search through vector find first person matching first initial , retrieve first name struct.
my research highlights need use overloaded operator person struct require guidance.
note: can use vector , find() algorithm. can't use boost.
#include <stdio.h> #include <iostream> #include <stdexcept> #include <vector> #include <algorithm> #include <string> using namespace std; struct person { char firstinitial; string firstname; person(const char fi, const string fn) { firstinitial = fi; firstname = fn; }; char getinitial() { return firstinitial; }; string getname() { return firstname; }; bool operator==(const person& l, const person& r) const { return l.firstinitial == r.firstinitial; } }; int main (int argc, char *argv[]) { vector<person> myvector; vector<person>::iterator itr; myvector.push_back(person('j', "john")); myvector.push_back(person('s', "steve")); myvector.push_back(person('c', "candice")); itr = find (myvector.begin(), myvector.end(), itr->getinitial() == 's'); if (itr != myvector.end()) cout << "first name: " << itr->getname() << '\n'; else cout << "not found" << '\n'; }
1.operator==()
should binary function. if want member function, should take 1 parameter, like:
bool operator==(const person& r) const { return firstinitial == r.firstinitial; }
or make non-member function (move out of class declaration):
bool operator==(const person& l, const person& r) { return l.firstinitial == r.firstinitial; }
2.std::find
expects 3rd argument value compared to, change to:
itr = find (myvector.begin(), myvector.end(), person('s', ""));