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

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   

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


merge (應用於有序區間)

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

描述:將兩個經過排序的集合S1和S2,合并起來置於另一段空間。所得結果也是一個有序(sorted)序列

思路:

1.遍曆兩個序列直到其中一個結束了

2.如果序列一的元素較小,將它放到結果序列中,並前進 1

3.如果序列二的元素較小,將它放到結果序列中,前前進 1

4.遍曆結束後,將還沒有遍曆完的序列複製到結果序列的尾部

複雜度:O(m+n)

源碼:
template <class InputIterator1, class InputIterator2, class OutputIterator>OutputIterator merge(InputIterator1 first1, InputIterator1 last1,                     InputIterator2 first2, InputIterator2 last2,                     OutputIterator result) {  while (first1 != last1 && first2 != last2) {    if (*first2 < *first1) {      *result = *first2;      ++first2;    }    else {      *result = *first1;      ++first1;    }    ++result;  }  return copy(first2, last2, copy(first1, last1, result)); // 之前一直不懂為什麼 copy 之類的演算法要返回一個指向 操作完後的序列的 last 的迭代器。這行代碼很好地解釋了原因}


樣本:
int main(){  int A1[] = { 1, 3, 5, 7 };  int A2[] = { 2, 4, 6, 8 };  const int N1 = sizeof(A1) / sizeof(int);  const int N2 = sizeof(A2) / sizeof(int);  merge(A1, A1 + N1, A2, A2 + N2,         ostream_iterator<int>(cout, " "));  // The output is "1 2 3 4 5 6 7 8"}


聯繫我們

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