find a member variable in a vector of objects cpp

Solutions on MaxInterview for find a member variable in a vector of objects cpp by the best coders in the world

showing results for - "find a member variable in a vector of objects cpp"
Tim
18 Jun 2020
1//Using a lambda function (only C++11 or newer)
2std::vector<Type> v = ....;
3std::string myString = ....;
4auto it = find_if(v.begin(), v.end(), [&myString](const Type& obj) {return obj.getName() == myString;})
5
6if (it != v.end())
7{
8  // found element. it is an iterator to the first matching element.
9  // if you really need the index, you can also get it:
10  auto index = std::distance(v.begin(), it);
11}
12
Chris
04 Feb 2018
1//Using a standard functor
2
3struct MatchString
4{
5 MatchString(const std::string& s) : s_(s) {}
6 bool operator()(const Type& obj) const
7 {
8   return obj.getName() == s_;
9 }
10 private:
11   const std::string& s_;
12};
13
similar questions