This article is original senlie. reprinted at this address:Http://blog.csdn.net/zhengsenlie
Search_n
Bytes ----------------------------------------------------------------------------------------
Description: In the range covered by the sequence [first, last), find the subsequence formed by "continuous count elements that meet the conditions,
And returns the iterator last.
Ideas:
1. First find the first occurrence point of Value
2. Whether the count-1 value continuously appears after the occurrence point
3. If yes, It is found. If not, refind the value occurrence point in the interval after the current element.
Figure 6-6 K
Template <class forwarditerator, class integer, class T> forwarditerator search_n (forwarditerator first, forwarditerator last, integer count, const T & Value) {If (count <= 0) return first; else {First = find (first, last, value); // first, locate the point where value appears for the first time while (first! = Last) {// is it better to write the condition here as last-first <n? Integer n = count-1; // value should also appear n times forwarditerator I = first; ++ I; while (I! = Last & n! = 0 & * I = value) {++ I; -- N ;}if (n = 0) // return first; else // not found, start searching for first = find (I, last, value);} return last;} again from I ;}}
Example:
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 issearching for a sequence of 1 '4': Not foundsearching 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 foundsearching for a (sign-insensitive) sequence of 1 '3': Index = 4 searching for a (sign-insensitive) sequence of 2 '3' S: Index = 4 */