c/c++ 标准库 插入迭代器 详解
生活随笔
收集整理的這篇文章主要介紹了
c/c++ 标准库 插入迭代器 详解
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
標準庫 插入迭代器 詳解
插入迭代器作用:copy等函數(shù)不能改變?nèi)萜鞯拇笮?#xff0c;所以有時copy先容器是個空的容器,如果不使用插入迭代器,是無法使用copy等函數(shù)的。
例如下面的代碼就是錯誤的:
list<int> lst{1,2,3,4}; list<int> lst2,lst3; copy(lst.cbegin(), lst.cend(), lst2.begin());lst2是個空的容器,copy函數(shù)不能擴容容器lst2,所以會發(fā)生運行時錯誤。
用插入迭代器就可以很好的解決上面的問題
list<int> lst{1,2,3,4}; list<int> lst2,lst3; copy(lst.cbegin(), lst.cend(), inserter(lst3, lst3.begin()));三種插入迭代器
back_inserter | 創(chuàng)建一個使用push_back的迭代器 |
front_inserter | 創(chuàng)建一個使用push_front的迭代器 |
inserter | 創(chuàng)建一個使用insert的迭代器,元素插入到指定位置之前 |
inserter的特殊之處:
//假設(shè)it是有inserter生成的迭代器 *it = val;//其效果同下面二行代碼一樣 it = c.insert(it, val);//it指向新加入的元素 ++it;//遞增it,使它指向原來的元素例子:
#include <iostream> #include <vector> #include <list> #include <algorithm>using namespace std;int main(){//copy函數(shù)不會改變?nèi)萜鞯拇笮?#xff0c;但是使用了插入迭代器后, //就會改變?nèi)萜鞯拇笮×? /* list<int> lst{1,2,3,4}; list<int> lst2,lst3; //運行錯誤,因為lst2是空list,copy函數(shù)不會增加容器的大小 //copy(lst.cbegin(), lst.cend(), lst2.begin()); //結(jié)果:4,3,2,1copy(lst.cbegin(), lst.cend(), front_inserter(lst2)); //結(jié)果:1,2,3,4 copy(lst.cbegin(), lst.cend(), inserter(lst3, lst3.begin())); for(auto const &s : lst2){ cout << s << " "; } cout << endl; for(auto const &s : lst3){ cout << s << " "; } cout << endl; *///unique_copy 拷貝不重復(fù)的元素到新的容器 vector<int> ivec{1,2,1,2,3,4,3,3,3,2,2,1,1,1};list<int> lst;sort(ivec.begin(),ivec.end());unique_copy(ivec.cbegin(), ivec.cend(),back_inserter(lst));for(auto const &s : lst){cout << s << " ";}cout << endl;}c/c++ 學(xué)習(xí)互助QQ群:877684253
本人微信:xiaoshitou5854
轉(zhuǎn)載于:https://www.cnblogs.com/xiaoshiwang/p/9684515.html
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的c/c++ 标准库 插入迭代器 详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

- 上一篇: [Poetize6] IncDec Se
- 下一篇: HTML常用的标签