This article Senlie original, reproduced please retain this address:Http://blog.csdn.net/zhengsenlie
Includes (applied to ordered interval)
-------------------------------------------------------------
Descriptive narrative: Both S1 and S2 must be orderly sets. Infer whether the sequence two S2 "covers" the sequence one S1, that is, whether each element of S2 appears in S1 "
Ideas:
1. Traverse two intervals. Until one of them is finished.
2. Assume that the element of sequence two is less than the element of sequence one. It is not possible to have elements equal to the current element of sequence two in sequence one, and return false directly
3. Assume that the element of sequence one is less than the element of sequence two. Then sequence one forward 1
4. Assuming that the two sequence elements are equivalent, all advance 1
5. When there is a sequence to go through. Infer whether the sequence of two is gone.
Complexity: Up to 2 * ((LAST1-FIRST1) + (LAST2-FIRST2))-1 times comparison
Source:
S1 and S2 are increment sequences.Operator < operation comparison operation//assuming that the randomaccessiterator can get the interval length, assuming that the length of the interval 1 is less than the interval 2 can return false early end loop//Just here is inputiterator, probably because of this There is little effect on efficiency, there is no optimized template <class InputIterator1 for randomaccessiterator in STL, Class Inputiterator2>bool includes ( InputIterator1 First1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2) {while (first1! = Last1 && First2! = last2)//Two intervals have not gone through if (*first2 < *first1)//sequence two elements less than sequence one element, return false return false;< C4/>else if (*first1 < *FIRST2)//sequence one element less than sequence two elements, sequence one forward 1 ++first1; else//Two sequence elements are equal, respectively advancing 1 ++first1, ++first2; return first2 = = Last2; There is a sequence gone, inference is whether the sequence two is gone, assuming that the coverage is set up, otherwise, not established}
Demo Sample:
int a1[] = {1, 2, 3, 4, 5, 6, 7};int a2[] = {1, 4, 7};int a3[] = {2, 7, 9};int a4[] = { 1, 1, 2, 3, 5, 8,};int a5[] = {1, 2,,};int a6[] = {1, 1, 3,};const int N1 = sizeof (A1)/sizeof (int) const int N2 = sizeof (A2)/sizeof (int), const int N3 = sizeof (A3)/sizeof (int), const int N4 = sizeof (A4)/sizeof (int); c onst int N5 = sizeof (A5)/sizeof (int), const int N6 = sizeof (A6)/sizeof (int), cout << "A2 contained in A1:" & lt;< (Includes (A1, A1 + N1, A2, A2 + N2)?
"true": "false") << Endl; Truecout << "A3 contained in A1:" << (Includes (A1, A1 + N2, A3, A3 + N3)? " True ":" false ") << Endl; Falsecout << "A5 contained in A4:" << (Includes (A4, A4 + N4, A5, A5 + N5)?
"true": "false") << Endl; Falsecout << "A6 contained in A4:" << (Includes (A4, A4 + N4, A6, A6 + N6)? " True ":" false ") << Endl; True
STL Source Code Analysis algorithm Stl_algo.h--includes