Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if strings in std::vector contain substring in C++

Tags:

c++

string

Is there an efficient way of executing a function if any string inside a vector contains a substring?

Something along these lines

if(vector.contains(strstr(currentVectorElement,"substring"))) {
    //do something
}

if(vector.contains(strstr(currentVectorElement,"substring2"))) {
    //do something else
}

The only thing I can think of is iterating over each string and check if the substring exists.

like image 646
Nick Avatar asked May 25 '16 13:05

Nick


1 Answers

You can use std::find_if with a lambda expression

if(std::find_if(vec.begin(), vec.end(), [](const std::string& str) { return str.find("substring") != std::string::npos; }) != vec.end()) {
    ...
}
like image 86
Smeeheey Avatar answered Sep 20 '22 20:09

Smeeheey