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

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   2014   

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


search

-------------------------------------------------------------------------

描述:在序列一[first1, last1) 所涵蓋的區間中,尋找序列二[first2, last2) 的首次出現點。
思路:
1.遍曆序列二
2.如果兩序列的當前元素一樣,都前進 1
3.否則序列二的迭代器重新指向開始元素,序列一前進 1 ,序列一的長度減 1
複雜度:
最壞情況是平方: 最多 (last1 - first1) * (last2 - first2) 次比較。 但最壞情況很少出現。
平均情況下是線性複雜度

源碼:

template <class ForwardIterator1, class ForwardIterator2>inline ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1,                               ForwardIterator2 first2, ForwardIterator2 last2){  return __search(first1, last1, first2, last2, distance_type(first1),                  distance_type(first2));}//沒看源碼之前,還以為會有什麼複雜的演算法,結果也只是遍曆//如果沒有假設(比如有序什麼的),STL裡的許多演算法實現也是挺普通的做法template <class ForwardIterator1, class ForwardIterator2, class Distance1,          class Distance2>ForwardIterator1 __search(ForwardIterator1 first1, ForwardIterator1 last1,                          ForwardIterator2 first2, ForwardIterator2 last2,                          Distance1*, Distance2*) {  Distance1 d1 = 0;  distance(first1, last1, d1);  Distance2 d2 = 0;  distance(first2, last2, d2);  if (d1 < d2) return last1; //如果第二序列大於第一序列,不可能成為其子序列  ForwardIterator1 current1 = first1;  ForwardIterator2 current2 = first2;  while (current2 != last2) // 我的第一感覺是遍曆第一序列,結果人家是遍曆第二序列。不過感覺代碼寫起來應該差不多    if (*current1 == *current2) { // 如果這個元素相同,調整,以便比對下一個元素      ++current1;      ++current2;    }    else { //如果這個元素不同      if (d1 == d2) //如果兩序列一樣長了,就不可能成功了        return last1;      else { //如果兩序列不一樣長,調整序列標兵        current1 = ++first1;        current2 = first2;        --d1; //已經排序了序列一的一個元素,所以序列一的長度要減 1      }    }  return first1;}


樣本:
const char S1[] = "Hello, world!";const char S2[] = "world";const int N1 = sizeof(S1) - 1;const int N2 = sizeof(S2) - 1;const char* p = search(S1, S1 + N1, S2, S2 + N2);printf("Found subsequence \"%s\" at character %d of sequence \"%s\".\n", S2, p - S1, S1);


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.