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

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   2014   

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


partition

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

描述:partition 會將區間[first,last) 中的元素重新排列。所有被一元條件運算 pred 判定為 true 的元素,都會被放在區間的前段,
被判定為 false 的元素,都會被放在區間的後段。
partition 不穩定,不保證 partition 後元素保留在原始相對位置, stable_partition 穩定
思路:
1.first往下尋找,遇到"符合移動條件"(pred不成立)的就停下來
2.last往上尋找,遇到"符合移動條件"(pred成立)的就停下來
3.交換 *first 和 *last, ++first, --last
圖6-6d
複雜度:O(n)
源碼:
//所有被 pred 判定為 true 的元素,都被放到前段//被 pred 判定為 false 的元素,都被放到後段//不保證保留相對位置template <class BidirectionalIterator, class Predicate>BidirectionalIterator partition(BidirectionalIterator first,                                BidirectionalIterator last, Predicate pred) {  while (true) {    while (true)      if (first == last)        return first;      else if (pred(*first))        ++first;      else        break;    --last;    while (true)      if (first == last)        return first;      else if (!pred(*last))        --last;      else        break;    iter_swap(first, last);    ++first;  }}


樣本:
int A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};const int N = sizeof(A)/sizeof(int);partition(A, A + N,          compose1(bind2nd(equal_to<int>(), 0),                   bind2nd(modulus<int>(), 2)));copy(A, A + N, ostream_iterator<int>(cout, " "));// The output is "10 2 8 4 6 5 7 3 9 1". 


聯繫我們

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