Reputation: 77
I want to search in a string some substrings using std::search
.
I tried this:
std::string str = "the quick brown fox jumps over the lazy dog";
std::string substr[] = { "fox","dog","bear" };
auto it = std::search(str.begin(), str.end(), substr, substr + 3);
std::cout << "substring found at position :" << (it - str.begin()) << std::endl;
And I have these errors :
operator_surrogate_func:no mathing overloaded function found
Failed to specialize function template 'unknown type std::equal_to<void>::operator()
Upvotes: 2
Views: 1165
Reputation: 23832
You have an array of substrings so you need to compare each one individually, std::search
can only look for one substring at a time.
std::string str = "the quick brown fox jumps over the lazy dog";
std::string substr[] = { "fox","dog","bear" };
for(auto& sstr : substr){
auto it = std::search(str.begin(), str.end(), sstr.begin(), sstr.end());
std::cout << "substring found at position :" << (it - str.begin()) << std::endl;
}
Note that if the substring is not found the return will be the .end()
iterator which points to one past the end of the string.
Upvotes: 3
Reputation: 8310
Because last two arguments of std::search
should be the iterators to the sequence of characters (to be more precise, your iterators, and reference types of your iterators must be comparable) you are looking for, and your substr
variable if an array of std::string
. So range [substr, substr+3)
doesn't actually represent your "fox" or "dog" or "bear, but the pointers to string "fox" and a pointer past the end of your array.
Try the following:
std::string str = "the quick brown fox jumps over the lazy dog";
std::string substr[] = { "fox","dog","bear" };
auto it = std::search(str.begin(), str.end(), substr[0].begin(), substr[0].end());
std::cout << "substring found at position :" << (it - str.begin()) << std::endl;
it = std::search(str.begin(), str.end(), substr[1].begin(), substr[1].end());
std::cout << "substring found at position :" << (it - str.begin()) << std::endl;
it = std::search(str.begin(), str.end(), substr[2].begin(), substr[2].end());
std::cout << "substring found at position :" << (it - str.begin()) << std::endl;
return 0;
First it will search your string for the occurence of "fox", then "dog" and then "bear". The "bear" is not found and the resulting iterator points to str.end()
.
Upvotes: 2