STL中常用的一些演算法函數[持續更新]

來源:互聯網
上載者:User

1 merge 歸併 將兩個數組合并成一個(有序) 

        merge(iarray1,iarray+len1,iarray2,iarray2+len2,result); 升序

        merge(iarray1,iarray+len1,iarray2,iarray2+len2,result,greater<int>()); 降序

2  reverse 元素反向

       reverse(iarray,iarray+len1);

3 reverse_copy 元素反轉複寫方向

       reverse(iarray,iarray+len,iarray_new);  複製到新的數組中

3 unique 剔除連續重複元素     ,剔除後元素的個數並不會減少,只是,後面的元素複製過來覆蓋前面被剔除的(#add 此演算法作用沒太明白,待解決),如下面的例子

      如果之前是 {1 ,2,3,3,4,4,5,6,6,8}

      result=unique(v.begin(),v.end()) ;  //#add 如果是數組記得要"越界"一下,比如int a[3]; 則要unique(&a[0],&a[3]);因為a[3]才相當於end迭代器。

      for_each(v.begin(),v.end(),print);  列印出來將是{1,2,3,4,5,6,8,6,6,8}  後面的元素依舊會存在

      for_each(v.begin(),result,print)     列印出來將是{1,2,3,4,5,6,8}

4 最小元素 min_element  返回[first,last) 中最小的元素

5 最大元素 max_element 返回[first,last) 中最大的元素

6 for_each(v.begin(),v.end(),print)      [v.begin(),v.end()) 裡的每一個元素 都執行一次 print函數

7 尋找容器元素  find

     在迭代器區間[first,last)之間尋找 元素值等於 value的  如果找到則返回 迭代器i 否則返回 last

     result=find(v.begin(),v.end(),value);

8 條件尋找容器元素  find_if

     檢查區間的每一個元素,如果滿足謂詞 pred(*i)==true 則返回 i;

     find_if(v.begin(),v.end(),pred)  pred為謂詞判斷函數

9 統計等於某值的容器元素個數 count

    num=count(v.begin(),v.end(),value)  返回  等於value的個數

10條件統計容器元素個數  count_if

     num=count_if(v.begin(),v.end(),pred)  返回滿足 謂詞pred判斷的個數

11子序列搜尋 search   若找到,則返回迭代器的值,否則返回last

     iterLocation=search(first1,last1,first2,last2)

12區間元素交換 swap_rangs

     swap_rangs(first1,last1,first2)   只要知道第二個的首地址就OK了,

13替換 replace

     replace(first,last,oldvalue,newvalue)

14條件替換 replace_if

     replace_if(first,last,odd,new)  odd 條件替換函數

15移除 remove

     result=remove(first,last,value)  為什麼要返回迭代器result呢,因為實際上只是將不等於value的元素複製到了[first,result)區間

                                                       而 [result,last)區間的元素依然不變

16條件移除 remove_if

        同上,只是加了一個謂詞判斷

聯繫我們

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