Defined in header <algorithm> | ||||
---|---|---|---|---|
| (1) | |||
| (2) |
Searches for the first occurrence of the subsequence of elements [s_first, s_last)
in the range [first, last - (s_last - s_first))
. The first version uses operator==
to compare the elements, the second version uses the given binary predicate p
.
Parameters
first, last | - | the range of elements to examine |
s_first, s_last | - | the range of elements to search for |
p | - | binary predicate which returns true if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following:
The signature does not need to have |
Type requirements | ||
- ForwardIt1, ForwardIt2 must meet the requirements of ForwardIterator . |
Return value
Iterator to the beginning of first subsequence [s_first, s_last)
in the range [first, last - (s_last - s_first))
. If no such subsequence is found, last
is returned.
If [s_first, s_last)
is empty, first
is returned. (since C++11).
Complexity
At most S*N
comparisons where S = std::distance(s_first, s_last)
and N = std::distance(first, last)
.
Possible implementation
First version | ||
---|---|---|
| ||
Second version | ||
|
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <string> #include <algorithm> #include <iostream> #include <vector> template < typename Container> bool in_quote( const Container& cont, const std::string& s) { return std::search(cont.begin(), cont.end(), s.begin(), s.end()) != cont.end(); } int main() { std::string str = "why waste time learning, when ignorance is instantaneous?" ; // str.find() can be used as well std::cout << std::boolalpha << in_quote(str, "learning" ) << '\n' << in_quote(str, "lemming" ) << '\n' ; std::vector< char > vec(str.begin(), str.end()); std::cout << std::boolalpha << in_quote(vec, "learning" ) << '\n' << in_quote(vec, "lemming" ) << '\n' ; } |
Output:
1 2 3 4 | true false true false |
See also
finds the last sequence of elements in a certain range (function template) | |
returns true if one set is a subset of another (function template) | |
determines if two sets of elements are the same (function template) | |
(C++11) | finds the first element satisfying specific criteria (function template) |
returns true if one range is lexicographically less than another (function template) | |
finds the first position where two ranges differ (function template) | |
searches for a number consecutive copies of an element in a range (function template) | |
std::experimental::search
(library fundamentals TS) | applies a searcher to a sequence (function template) |
std::experimental::parallel::search
(parallelism TS) | parallelized version of std::search (function template) |
Please login to continue.