Dimitris Sfounis Dimitris Sfounis - 3 months ago 19
C++ Question

Finding if a vector of pair<string,string> contains pairs that match on the first string

Right, I know the title is pretty convoluted, so I'll try to explain my situation:

I have a vector of pairs of strings,

std::vector< std::pair<std::string, std::string> >
which contains pairs of names and surnames.

Is there a go-to simple way of using
find
or
find_if
to get all pairs in my
vector
that match only on the first part of the pairs?

For example, if my vector contains the pairs:

John Doe
Ivan Ivanovitch
Richard Stallman


is there a way to use
find
or
find_if
to check if my vector contains any
pair
s that match with the first name
John
, disregarding the last name (which I will use later on)?

Suppose that my vector only contains distinctly different names and surnames and there's never pairs that have the same
first
, meaning no two
John
s or
Richard
s.

Answer
std::find_if(vec.begin(), vec.end(), [](std::pair<std::string, std::string> const & elem)
                                     {
                                          return elem.first == "John";
                                     });

You can compare the return value with vec.end() to see if the find succeeded