6

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? May 25, 2016 at 13:05
  • @KarstenKoop speed optimized so low running time
    – Nick
    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... 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.
    – Slava
    May 25, 2016 at 13:55

2 Answers 2

8

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()) {
    ...
}
1
  • 9
    std:any_of might make more sense here. May 25, 2016 at 13:10
1

What you need is std::search()

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.