Search code examples
c++vectorstl-algorithm

Search for a variable from vector of objects


struct ABC
{
int a;
string b;
};

I have a vector of objects to the above struct. And want to search the vector based on variable "b"?

I have logic as below.

vector<ABC> vec = ...;//vec has my objects
for(vector<ABC>::iterator it = vec.begin();
        it != vec.end();
        ++it)
    {
        if(search_str == (it->b))//search string is my string which i need to search
        {
        }
    }

I have extensively tested the above code and it works. I want to know if there is a better way to achieve this. Maybe using find().


Solution

  • Simple, readable, lifted from Sam's comment:

    auto found = std::find_if(vec.begin(), vec.end(), [&](auto const &e) {
        return e.b == search_str;
    });
    

    And now found is an iterator to the first matching element, or vec.end() if none was found.