STL 源碼剖析 演算法 stl_algo.h -- includes

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   io   

本文為senlie原創,轉載請保留此地址:http://blog.csdn.net/zhengsenlie


includes(應用於有序區間)
-------------------------------------------------------------


描述:S1和S2都必須是有序集合,判斷序列二 S2 是否"涵蓋於"序列一 S1,即"S2的每一個元素是否都出現於 S1中"
思路:
1.遍曆兩個區間,直到其中一個走完
2.如果序列二的元素小於序列一的元素,則在序列一中不可能有元素等於序列二的當前元素了,直接返回 false
3.如果序列一的元素小於序列二的元素,則序列一前進 1
4.如果兩序列元素相當,都前進 1
5.當有一個序列走完時,判斷序列二是否走完了。
圖6-6b
複雜度:最多 2 * ((last1- first1) + (last2 - first2)) - 1次比較
源碼:

// S1 和 S2是遞增序列。以 operator < 執行比較操作// 如果是 RandomAccessIterator 可以得到區間長度,如果區間1的長度小於區間2的可以返回 false 提前結束迴圈// 不過這裡是 InputIterator , 可能是因為這點對效率影響不大吧, stl裡沒有專門針對 RandomAccessIterator 的最佳化 template <class InputIterator1, class InputIterator2>bool includes(InputIterator1 first1, InputIterator1 last1,              InputIterator2 first2, InputIterator2 last2) {  while (first1 != last1 && first2 != last2) // 兩個區間都尚未走完    if (*first2 < *first1) // 序列二的元素小於序列一的元素,返回 false      return false;    else if(*first1 < *first2) // 序列一的元素小於序列二的元素,序列一前進 1       ++first1;    else //兩序列元素相等,各自前進 1      ++first1, ++first2;  return first2 == last2; //有一個序列走完了,判斷是序列二是否走完了,如果是,涵蓋情況成立,否則,不成立}

樣本:
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, 13, 21 };int A5[] = { 1, 2, 13, 13 };int A6[] = { 1, 1, 3, 21 };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);const int N5 = sizeof(A5) / sizeof(int);const int N6 = sizeof(A6) / sizeof(int);cout << "A2 contained in A1: "      << (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



 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.