Nick
Nick

Reputation: 2980

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

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.

Upvotes: 8

Views: 10719

Answers (2)

rep_movsd
rep_movsd

Reputation: 6895

What you need is std::search()

http://en.cppreference.com/w/cpp/algorithm/search

Upvotes: 1

Smeeheey
Smeeheey

Reputation: 10326

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()) {
    ...
}

Upvotes: 10

Related Questions