类别:算法 | 组件类型:函数 |
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);
第一个版本search返回第一个迭代器i在范围内[first, last - count) [2] 对于每个迭代器j在范围内[i, i + count), *j == value。第二个版本返回第一个迭代器i在范围内[first, last - count)对于每个迭代器j在范围内[i, i + count), binary_pred(*j, value)是true.
(C++ 标准允许复杂性为 O(n (last - first)),但这没有必要那么宽松。没有理由search_n多次检查任何元素。
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); }
输出是
Searching for a sequence of 1 '4': Not found Searching for a sequence of 0 '4's: Index = 0 Searching for a sequence of 1 '1': Index = 0 Searching for a sequence of 2 '1's: Index = 2 Searching for a sequence of 3 '1's: Index = 6 Searching for a sequence of 4 '1's: Index = 6 Searching for a sequence of 1 '3': Index = 4 Searching for a sequence of 2 '3's: Not found Searching for a (sign-insensitive) sequence of 1 '3': Index = 4 Searching for a (sign-insensitive) sequence of 2 '3's: Index = 4
[1] 请注意count允许为零:一个由零个元素组成的子序列是明确定义的。如果使用search_n呼叫count等于零,则搜索将始终成功:无论value是什么,每个范围都包含一个零连续元素的子范围,而这些连续元素都等于value。当search_n呼叫时count等于零,返回值始终为first.
[2] 范围是[first, last - count)而不是[first, last),原因是我们正在寻找长度为count的子序列;一个迭代器i除非last - 计数大于或等于count,否则不能成为这类的起始。注意这样做含有的意义:您可以使用search_n带参数来,使得last - first小于count,但这样的搜索会一直失败。