概述
关注小韩 轻松编程 一起由浅入深
解析都在代码里 废话不多说 上菜!!!
#include<iostream>
#include<deque>
using namespace std;
//deque容器插入和删除
/*
两端插入操作:
push_back(elem)
容器尾部插入数据
push_front(elem)
容器头部插入数据
pop_back()
删除容器最后一个元素
pop_front()
删除容器第一个元素
指定位置操作:
insert(pos,elem)
在pos位置插入一个elem元素的拷贝 返回新数据的位置
insert(pos,n,elem)
在pos位置插入n个elem数据 无返回值
insert(pos,beg(),end())
在pos位置插入区间元素 无返回值
clear()
清空容器所有数据
erase(beg, end)
删除区间数据 返回下一个数据的位置
erase(pos)
删除pos位置的数据 返回下一个数据的位置
*/
void dequeprint(const deque<int> & d)
{
for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++)
//注意const后有下划线————————-
cout << *it << " ";
cout << endl << endl;
}
//两端操作
void test()
{
deque<int> d1;
//尾插:
d1.push_back(10);
d1.push_back(20);
//头插:
d1.push_front(100);
d1.push_front(200);
// 200
100
10
20
dequeprint(d1);
//尾删
d1.pop_back();
//头删
d1.pop_front();
//100
10
dequeprint(d1);
cout << endl << endl << endl << endl << endl;
}
void
test1()
{
deque<int> d2;
d2.push_back(10);
d2.push_back(20);
d2.push_front(100);
d2.push_front(200);
cout << "d2原型:" << endl ;// 200
100
10
20
dequeprint(d2);
//insert()插入
d2.insert(d2.begin(),999);
//注意第一个参数得是迭代器
cout << "d2头部插入999:" << endl;//999
200
100
10
20
dequeprint(d2);
d2.insert(d2.begin(),2, 888);
cout << "d2头部插入两个888:" << endl;//888
888
999
200
100
10
20
dequeprint(d2);
//按照区间内插入元素
deque<int> d3;
d3.push_back(1);
d3.push_back(2);
d3.push_back(3);
d2.insert(d2.begin(),d3.begin(), d3.end()); //三个参数:1 插入位置
2.区间起点
3.区间终点
cout << "d2头部插入d2( 1 2 3 ):" << endl;// 1
2
3
888
888
999
200
100
10
20
dequeprint(d2);
//删除
deque<int>::iterator
it = d2.begin();
//利用it找指定位置
it++;
//it指向第一个位置
d2.erase(it);
cout << "擦除第二个位置的元素;" << endl;// 1
3
888
888
999
200
100
10
20
dequeprint(d2);
//利用区间删除
d2.erase(d2.begin(), d2.end());
cout << "擦除所有元素;" << endl;
dequeprint(d2);
}
int main()
{
test();
test1();
return 0;
}
最后
以上就是狂野信封为你收集整理的c++ deque容器 插入和删除操作 详解示例的全部内容,希望文章能够帮你解决c++ deque容器 插入和删除操作 详解示例所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复