Answers for "find a member variable in a vector of objects cpp"

C++
0

find a member variable in a vector of objects cpp

//Using a lambda function (only C++11 or newer)
std::vector<Type> v = ....;
std::string myString = ....;
auto it = find_if(v.begin(), v.end(), [&myString](const Type& obj) {return obj.getName() == myString;})

if (it != v.end())
{
  // found element. it is an iterator to the first matching element.
  // if you really need the index, you can also get it:
  auto index = std::distance(v.begin(), it);
}
Posted by: Guest on July-23-2021
0

find a member variable in a vector of objects cpp

//Using a standard functor

struct MatchString
{
 MatchString(const std::string& s) : s_(s) {}
 bool operator()(const Type& obj) const
 {
   return obj.getName() == s_;
 }
 private:
   const std::string& s_;
};
Posted by: Guest on July-23-2021

Code answers related to "find a member variable in a vector of objects cpp"

Browse Popular Code Answers by Language