Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find an element in a vector of vectors

Tags:

c++

I want to find string x in vector of vectors v:

std::vector<std::string> vA{"A", "B", "C"};
std::vector<std::string> vB{"D", "E", "F"};

std::string x = "E";
std::vector<std::vector<std::string>> v{vA, vB};

How to use std::find for my case ? Do you have some other ideas ?

Edit A result that bool value which indicates that at least one "E" has been found.

I wonder if it is possible to use somehow std::find* this way:

std::find*(v.begin(), v.end(), /*lambda with next std::find*/) 
like image 343
Irbis Avatar asked Dec 11 '25 14:12

Irbis


1 Answers

Keep it simple:

for (auto const &stringVector : v) {
    auto it = std::find(std::begin(stringVector), std::end(stringVector), x);
    if (it != std::end(stringVector)) {
         // do what you want
         break;
    }
}

I'd like to make a comment, perhaps as a side-note. Your title asks "How to find an element in a vector of vectors". Your question, however, asks "How to use std::find for my case?"

You shouldn't use std::find because that's what you're "supposed to do". Use it when it's helpful, and avoid it when its harmful. Start from your data, not from the code.

EDIT

To answer your edit, you can use std::find_if.

using namespace std;

bool find_string(vector<vector<string>> const &v, string const &x) {
    return find_if(begin(v), end(v), [&x] (vector<string> const &stringVector) {
        return find(begin(stringVector), end(stringVector), x) == end(stringVector);
    }) != end(v);
}

But this is less readable in my view.

like image 196
nasser-sh Avatar answered Dec 14 '25 02:12

nasser-sh