8

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.

4
  • Do you mean efficient in the sense of low number of code lines or low running time? Commented May 25, 2016 at 13:05
  • @KarstenKoop speed optimized so low running time Commented May 25, 2016 at 13:19
  • For that it doesn't matter if you loop by hand or use something like std::find_if as mentioned below, you still loop over all elements. You would have to use something other than a vector. If you were not looking for substrings, but could compare the whole string, you could use an unordered_map, but with substrings it's difficult... Commented May 25, 2016 at 13:22
  • Efficiency achieved mostly by proper algorithms and data structures. For vector of string the only way is iterating over all elements. If performance of this search is important you should think about different data structure, for example radix tree. Commented May 25, 2016 at 13:55

2 Answers 2

10

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()) {
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

std:any_of might make more sense here.
1

What you need is std::search()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.