search_n
Category: algorithms
Component type: function
template<class ForwardIterator, class Integer, class T>
ForwardIterator search_n(ForwardIterator first, ForwardIterator last, Integer count, const T& value);
template<class ForwardIterator, class Integer, class T, class BinaryPredicate>
ForwardIterator search_n (ForwardIterator first, ForwardIterator last, Integer count, const T& value, BinaryPredicate binary_pred);
The first version of
Defined in the standard header algorithm, and in the nonstandard backward-compatibility header algo.h.
For the first version:
• Objects of
For the second version:
Linear.
(The C++ standard permits the complexity to be
bool eq_nosign(int x, int y) { return abs(x) == abs(y); }
void lookup(int* first, int* last, size_t count, int val) {
cout << 'Searching for a sequence of ' << count << ' '' << val << ''' << (count != 1 ? 's: ' : ': ');
int* result = search_n(first, last, count, val);
if (result == last) cout << 'Not found' << endl;
else cout << 'Index = ' << result – first << endl;
}
void lookup_nosign(int* first, int* last, size_t count, int val) {
cout << 'Searching for a (sign-insensitive) sequence of ' << count << ' '' << val << ''' << (count != 1 ? 's: ' : ': ');
int* result = search_n(first, last, count, val, eq_nosign);
if (result == last) cout << 'Not found' << endl;
else cout << 'Index = ' << result – first << endl;
}
int main() {
const int N = 10;
int A[N] = {1, 2, 1, 1, 3, –3, 1, 1, 1, 1};
lookup(A, A+N, 1, 4);
lookup(A, A+N, 0, 4);
lookup(A, A+N, 1, 1);
lookup(A, A+N, 2, 1);
lookup(A, A+N, 3, 1);
lookup(A, A+N, 4, 1);
lookup(A, A+N, 1, 3);
lookup(A, A+N, 2, 3);
lookup_nosign(A, A+N, 1, 3);
lookup_nosign(A, A+N, 2, 3);
}
The output is
Searching for a sequence of 1 '4': Not found
Searching for a sequence of 0 '4's: Index = 0
