std::search
Defined in header <algorithm>
|
||
template< class ForwardIterator1, class ForwardIterator2 > ForwardIterator1 search( ForwardIterator1 first, ForwardIterator1 last, |
(1) | |
template< class ForwardIterator1, class ForwardIterator2, class BinaryPredicate > ForwardIterator1 search( ForwardIterator1 first, ForwardIterator1 last, |
(2) | |
Searches for the first 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.
Contents |
[edit] 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 const &, but the function must not modify the objects passed to it. |
[edit] 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)
[edit] Complexity
At most S*N comparisons where S = std::distance(s_first, s_last) and N = std::distance(first, last).
[edit] Possible implementation
First version |
---|
template<class ForwardIterator1, class ForwardIterator2> ForwardIterator1 search(ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 s_first, ForwardIterator2 s_last) { for (; ; ++first) { ForwardIterator1 it = first; for (ForwardIterator2 s_it = s_first; ; ++it, ++s_it) { if (s_it == s_last) { return first; } if (it == last) { return last; } if (!(*it == *s_it)) { break; } } } } |
Second version |
template<class ForwardIterator1, class ForwardIterator2, class BinaryPredicate> ForwardIterator1 search(ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 s_first, ForwardIterator2 s_last, BinaryPredicate p) { for (; ; ++first) { ForwardIterator1 it = first; for (ForwardIterator2 s_it = s_first; ; ++it, ++s_it) { if (s_it == s_last) { return first; } if (it == last) { return last; } if (!p(*it, *s_it)) { break; } } } } |
[edit] Example
This section is incomplete |
[edit] See also
finds the last sequence of elements in a certain range (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) |