Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search a vector of objects by object attribute

Tags:

c++

std

gcc

stl

I'm trying to figure out a nice way to find the index of a certain object in a vector - by comparing a string to a member field in the object.

Like this:

find(vector.begin(), vector.end(), [object where obj.getName() == myString]) 

I have searched without success - maybe I don't fully understand what to look for.

like image 316
Christoffer Avatar asked Mar 20 '13 07:03

Christoffer


People also ask

How do you find the vector of an object?

Finding an element in vector using STL Algorithm std::find() Basically we need to iterate over all the elements of vector and check if given elements exists or not. This can be done in a single line using std::find i.e. std::vector<int>::iterator it = std::find(vecOfNums.

How do you search within a vector?

You can use the find function, found in the std namespace, ie std::find . You pass the std::find function the begin and end iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.

How do you access a specific element in a vector?

Element access: reference operator [g] – Returns a reference to the element at position 'g' in the vector. at(g) – Returns a reference to the element at position 'g' in the vector. front() – Returns a reference to the first element in the vector. back() – Returns a reference to the last element in the vector.

What does Find_if return?

C++ Algorithm find_if() function returns the value of the first element in the range for which the pred value is true otherwise the last element of the range is given.


1 Answers

You can use std::find_if with a suitable functor. In this example, a C++11 lambda is used:

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); } 

If you have no C++11 lambda support, a functor would work:

struct MatchString {  MatchString(const std::string& s) : s_(s) {}  bool operator()(const Type& obj) const  {    return obj.getName() == s_;  }  private:    const std::string& s_; }; 

Here, MatchString is a type whose instances are callable with a single Type object, and return a boolean. For example,

Type t("Foo"); // assume this means t.getName() is "Foo" MatchString m("Foo"); bool b = m(t); // b is true 

then you can pass an instance to std::find

std::vector<Type>::iterator it = find_if(v.begin(), v.end(), MatchString(myString)); 
like image 197
juanchopanza Avatar answered Oct 14 '22 14:10

juanchopanza