【STL】inserter和front_inserter的用法

來源:互聯網
上載者:User
#include <iostream> #include <algorithm> #include <list>  using namespace std;  int iArray[5] = { 1, 2, 3, 4, 5 }; void Display(list<int>& a, const char* s) {   cout << s << endl;   copy(a.begin(), a.end(),ostream_iterator<int>(cout, " "));   cout << endl; }int main() {   list<int> iList;copy(iArray, iArray + 5, front_inserter(iList));   Display(iList, "Before find and copy"); list<int>::iterator p = find(iList.begin(), iList.end(), 3);copy(iArray, iArray + 2, inserter(iList, p));   Display(iList, "After find and copy");    return 0; }  

 

Before find and copy
5 4 3 2 1
After find and copy
5 4 1 2 3 2 1
請按任意鍵繼續. . .

 

#include<iostream>#include<algorithm>#include<vector>using namespace std;class myclass{public:friend ostream &operator << (ostream &, const myclass &);     myclass(int a,int b):first(a),second(b) { }     int first;     int second;     bool operator < (const myclass &m) const      {          return first < m.first;     }     }; //reloadostream &operator << (ostream &out,const myclass &mc){out << mc.first << " " <<mc.second <<endl;return out;}bool less_second(const myclass &m1,const myclass &m2){return m1.second<m2.second;}void Display(vector<myclass> &v, const char* s)   {         cout << endl << s << endl;         copy(v.begin(), v.end(),ostream_iterator<myclass>(cout," "));         cout << endl;   }  int main(){    int i=0;    vector<myclass> vct;    for(i=0;i<10;i++)    {            myclass my(10-i,i*3);            vct.push_back(my);    }Display(vct,"Initial");    sort(vct.begin(),vct.end()); //按第1個值排序 Display(vct,"after sorted by the  first:");    sort(vct.begin(),vct.end(),less_second);//按第2個值排序Display(vct,"after sorted by the  second: ");    system("pause");               return 0;}

 

Initial
10 0
 9 3
 8 6
 7 9
 6 12
 5 15
 4 18
 3 21
 2 24
 1 27

after sorted by the  first:
1 27
 2 24
 3 21
 4 18
 5 15
 6 12
 7 9
 8 6
 9 3
 10 0

after sorted by the  second:
10 0
 9 3
 8 6
 7 9
 6 12
 5 15
 4 18
 3 21
 2 24
 1 27

請按任意鍵繼續. . .

 

 

聯繫我們

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