stl非變易演算法(一),stl變易演算法

來源:互聯網
上載者:User

stl非變易演算法(一),stl變易演算法

C++ STL的非變易演算法是一組不破壞操作資料的模板函數,用來對序列資料進行逐個處理、元素尋找、子序列搜尋、統計和匹配。非變易演算法具有極為廣泛的適用性,基本上可應用於各種容器。

逐個容器元素for_each

C++ STL提供了一個for_each函數,用於對容器的元素進行迴圈操作。它對迭代區間[first, last)所指的每一個元素,執行由單參函數對象fn所定義的操作。原型如下:

template<class InputIterator, class Function>  Function for_each(InputIterator first, InputIterator last, Function fn){  while (first!=last) //迴圈遍曆  {    fn (*first);//調用fn進行操作    ++first;  }  return fn;  }
//執行個體#include <algorithm>#include <list>#include <iostream>using namespace std;struct print{    int count; //列印的元素計數    print(){count=0;}    void operator()(int x){        cout << 3*x << endl;        count++;    }};int main(void){    //雙向鏈表初始化    list<int> l;    l.push_back(29);    l.push_back(32);    l.push_back(16);    l.push_back(22);    l.push_back(27);    //列印鏈表的元素    print p=for_each(l.begin(),l.end(),print());    //列印的元素個數    cout << p.count << endl;    return 0;}

尋找容器元素find

find演算法函數用來尋找等於某值的元素。它在迭代器區間[first,last)上尋找等於value值的元素,如果迭代器i所指的元素滿足*i==value,則返回迭代器i。未找到滿足條件的元素,返回last。

//find演算法函數的代碼template<class InputIterator, class T>  InputIterator find (InputIterator first, InputIterator last, const T& val){  while (first!=last) {    if (*first==val) return first;    ++first;  }  return last;}
//執行個體#include <algorithm>#include <list>#include <iostream>int main(void){    using namespace std;    //雙向鏈表初始化    list<int> l;    l.push_back(10);    l.push_back(18);    l.push_back(26);    l.push_back(26);    l.push_back(30);    //尋找元素26    list<int>::iterator iLocation=find(l.begin(),l.end(),26);    if(iLocation != l.end())        cout << "找到元素26" << endl;    //列印元素18    cout << "前一個元素為" << *(--iLocation) << endl;    return 0;}

條件尋找容器元素find_if

find_if演算法函數是find的一個判斷版本,它利用bool值謂詞判斷pred,檢查迭代區間[first,last)上的每一個元素,如果迭代器i滿足pred(*i)==true,表示找到元素並返回迭代器i;未找到元素,返回末位置last。

template<class InputIterator, class UnaryPredicate>  InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred){  while (first!=last) {    if (pred(*first)) return first;    ++first;  }  return last;}
//執行個體#include <algorithm>#include <vector>#include <iostream>bool divby5(int x){    return x % 5 ? 0 : 1;}int main(void){    using namespace std;    //初始化vector    vector<int> v(20);    for(unsigned int i=0; i<v.size(); i++)        v[i]=(i+1)*(i+3);    vector<int>::iterator iLocation;    iLocation=find_if(v.begin(), v.end(), divby5);    if(iLocation != v.end())        cout << "找到第一個能被5整除的元素"         << *iLocation << endl           << "元素的索引位置為"        << iLocation - v.begin() << endl;     system("pause");    return 0;}

鄰近尋找容器元素adjacent_find

adjacent_find演算法函數用於尋找相等或滿足條件的鄰近元素對。它有兩個使用原型如下:

  • 在迭代區間[first,last)上尋找到有兩個連續的元素相等,就返回頭一個元素的迭代器位置。
template <class ForwardIterator>   ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last){  if (first != last)  {    ForwardIterator next=first; ++next;    while (next != last) {      if (*first == *next)             return first;      ++first; ++next;    }  }  return last;}
  • 使用二元謂詞判斷binary_pred,尋找[first,last)迭代器區間中滿足binary_pred謂詞判斷的鄰近元素對。
template<class ForwardIter, class BinaryPredicate>ForwardIter adjacent_find(ForwardIter first, ForwardIter last,BinaryPredicate binary_pred){    if (first==last)        return last;    ForwardIter next=first;    while(++next!=last)    {        if (binary_pred(*first,*next))//兩個鄰近元素是否滿足binary_pred條件            return first;        first=next;    }    return last;}
//執行個體#include <algorithm>#include <list>#include <iostream>bool parity_equal(int x, int y){    return (x-y)%2 == 0 ? 1:0;}int main(void){    using namespace std;     //鏈表初始化    list<int> l;    l.push_back(3);    l.push_back(6);    l.push_back(9);    l.push_back(11);    l.push_back(11);    l.push_back(18);    l.push_back(20);    l.push_back(20);    //尋找鄰接相等的元素    list<int>::iterator iResult=adjacent_find(l.begin(),l.end());    if(iResult != l.end()){        cout << "發現鏈表有兩個鄰接的元素相等:" << endl;        cout << *iResult << endl;        iResult++;        cout << *iResult << endl;    }    //尋找奇偶性相同的鄰接元素    iResult=adjacent_find(l.begin(), l.end(), parity_equal);    if(iResult != l.end()){        cout << "發現有兩個鄰接元素的奇偶性相同: " << endl;        cout << *iResult << endl;        iResult++;        cout << *iResult << endl;    }    system("pause");    return 0;}

範圍尋找容器元素find_first_of

find_first_of演算法用於尋找位於某個範圍之內的元素,它有如下兩個原型,均在迭代器區間[first1,last1)上尋找元素*i,使得迭代器區間[first2,last2)有某個元素*j,滿足*i==*j或滿足二元謂詞判斷comp(*i,*j)==true的條件。元素找到返回迭代器i,否則返回末位置last1。

template <class ForwardIterator1, class ForwardIterator2>   ForwardIterator1 find_first_of (ForwardIterator1 first1, ForwardIterator1 last1,template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>   ForwardIterator1 find_first_of (ForwardIterator1 first1, ForwardIterator1 last1,    ForwardIterator2 first2, ForwardIterator2 last2,BinaryPredicate pred);
//find_first_of演算法函數的代碼template<class InputIterator, class ForwardIterator>  InputIterator find_first_of ( InputIterator first1, InputIterator last1,                                ForwardIterator first2, ForwardIterator last2){  while (first1!=last1) {    for (ForwardIterator it=first2; it!=last2; ++it) {      if (*it==*first1)          // or: if (pred(*it,*first)) for version (2)        return first1;    }    ++first1;  }  return last1;}            
//執行個體#include <algorithm>#include <iostream>int main(void){    using namespace std;    //定義兩個字串    char* string1="abcdef7ghijklmn";    char* string2="zyx3pr7ys";    //範圍尋找string1於string2中    char* result=find_first_of(string1, string1 +             strlen(string1),        string2, string2 + strlen(string2));    cout << "字串string1的第一個出現在string2的字元為:"        << *result << endl;      return 0;}           

未完待續……

轉載請註明出處:http://blog.csdn.net/lsh_2013/article/details/46846027

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

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