当前位置: 代码迷 >> 综合 >> deque-insert
  详细解决方案

deque-insert

热度:26   发布时间:2023-12-15 04:29:51.0

iterator insert(iterator it,const T& x):双端队列中某一元素前增加一个元素x
返回安插点的位置
源码如下:

....
*pos = x_cpoy;
return  *pos; //pos即为新插入点的位置

// 2018/04/24 7:38:54
// deque-insert
// 在pos之前插入数据
#include <iostream>
#include <deque>
#include <iterator>
#include <algorithm>using namespace std;template<class T>
class Print{
    
public:void operator()(T& t){
    cout << t << " ";}
};
//=========================int main(){
    int ary[5] = {
     1, 2, 3, 4, 5 };//fill(ary, ary + 5, 1);deque<int> d;deque<int>::iterator it;Print<int> print;copy(ary,ary+5,back_inserter(d));cout << "deque d:" << endl;for_each(d.begin(),d.end(),print);cout << endl;it = d.begin();// insert value "5" at the position "it"cout << "d.insert(it,5)" << endl;d.insert(it, 5);for_each(d.begin(),d.end(),print);cout << endl;// insert range ary+2 - ary+5 at the position "it"it = d.begin() + 5;cout << "d.insert(it,ary+2,ary+5)" << endl;// it 指向 5 1 2 3 4 5 中的最后一个5,并向其前加入元素// ary+2 ~ ary+5, 也就是 3 4 5d.insert(it, ary + 2, ary + 5);for_each(d.begin(),d.end(),print);cout << endl;// insert 2 value of "20" at the position "it"it = d.end() - 2;cout << "d.insert(it,2,20)" << endl;d.insert(it, 2, 20);for_each(d.begin(),d.end(),print);cout << endl;return 0;
}/* OUTPUT:deque d:1 2 3 4 5d.insert(it,5)5 1 2 3 4 5d.insert(it,ary+2,ary+5)5 1 2 3 4 3 4 5 5d.insert(it,2,20)5 1 2 3 4 3 4 20 20 5 5 */ 
  相关解决方案