c++ - find a value in a vector of class objects -
i have written class-based vector:
class { private: string b; string c; public: a(string n, string l) { b = l ;c = n; } struct finder { finder(std::string const& n) : name(n) { } bool operator () ( const & el) const { return el.b == name; } private: std::string name; }; }; int main() { vector<a> a1; a1.push_back(a("aa","aa")); a1.push_back(a("bb","bb")); a1.push_back(a("cc","cc")); a1.push_back(a("dd","dd")); vector<string>::iterator it; = find_if(a1.begin(), a1.end(), a::finder("cc")); if (it != a1.end()) { auto pos = - a1.begin(); cout << "cc found @ " << pos ; } }
now, want search value in a1. let's want find index of element in "cc" happens.
i found these similar solutions:
search vector of objects object attribute
how can find object in vector based on class properties?
how find object specific field values in std::set?
as implement comments in section, still errors! did miss? guess problem in defining vector::iterator it;
error c2679: binary '=' : no operator found takes right-hand operand of type 'std::_vector_iterator<_myvec>' (or there no acceptable conversion)
and,
error c2678: binary '!=' : no operator found takes left-hand operand of type 'std::_vector_iterator<_myvec>' (or there no acceptable conversion)
you have use standard algorithm std::find_if
it = find_if(a1.begin(), a1.end(), a::finder("cc"));
take account inner clas should defined like
struct finder { finder(std::string const& n) : name(n) { } bool operator () ( const & el) const { return el.b == name; } private: std::string name; };
Comments
Post a Comment