标签:
deque采用模板类实现,deque对象的默认构造形式:deque<T> deq;
deque <int> deqInt; //一个存放int的deque容器。
deque <float> deq Float; //一个存放float的deque容器。
3.deque对象的带参数构造
#include<iostream>
using namespace std;
#include <deque>
void objPlay3()
{
deque<int> deqIntA;
deqIntA.push_back(1);
deqIntA.push_back(3);
deqIntA.push_back(5);
deqIntA.push_back(7);
deqIntA.push_back(9);
deque<int> deqIntB(deqIntA.begin(), deqIntA.end()); //1 3 5 7 9
deque<int> deqIntC(5, 8); //8 8 8 8 8
deque<int> deqIntD(deqIntA); //1 3 5 7 9
}
int main()
{
objPlay3();
return 0;
}
void objPlay4()
{
deque<int> deqIntA, deqIntB, deqIntC, deqIntD;
deqIntA.push_back(1);
deqIntA.push_back(3);
deqIntA.push_back(5);
deqIntA.push_back(7);
deqIntA.push_back(9);
deqIntB.assign(deqIntA.begin(), deqIntA.end()); // 1 3 5 7 9
deqIntC.assign(5, 8); //8 8 8 8 8
deqIntD = deqIntA; //1 3 5 7 9
deqIntC.swap(deqIntD); //C 和 D互换
}
5.deque的大小
void objPlay5()
{
deque<int> deqIntA;
deqIntA.push_back(1);
deqIntA.push_back(3);
deqIntA.push_back(5);
int iSize = deqIntA.size(); //3
if (!deqIntA.empty())
{
deqIntA.resize(5); //1 3 5 0 0
deqIntA.resize(7, 1); //1 3 5 0 0 1 1
deqIntA.resize(2); //1 3
}
}
6.deque末尾的添加移除操作
void objPlay6()
{
deque<int> deqInt;
deqInt.push_back(1);
deqInt.push_back(3);
deqInt.push_back(5);
deqInt.push_back(7);
deqInt.push_back(9);//此时1,3,5,7,9
deqInt.pop_front(); //弹出头部第一个元素
deqInt.pop_front();
deqInt.push_front(11);//头部添加元素
deqInt.push_front(13);
deqInt.pop_back(); //弹出最后一个 元素
deqInt.pop_back();
}
void objPlay7()
{
deque<int> deqInt;
deqInt.push_back(1);
deqInt.push_back(3);
deqInt.push_back(5);
deqInt.push_back(7);
deqInt.push_back(9);
int iA = deqInt.at(0); //1
int iB = deqInt[1]; //3
deqInt.at(0) = 99; //99
deqInt[1] = 88; //88
int iFront = deqInt.front();//99
int iBack = deqInt.back(); //9
deqInt.front() = 77; //77
deqInt.back() = 66; //66
}
8.deque的插入
void objPlay8()
{
deque<int> deqA;
deque<int> deqB;
deqA.push_back(1);
deqA.push_back(3);
deqA.push_back(5);
deqA.push_back(7);
deqA.push_back(9);
deqB.push_back(2);
deqB.push_back(4);
deqB.push_back(6);
deqB.push_back(8);
deqA.insert(deqA.begin(), 11); //{11, 1, 3, 5, 7, 9}
deqA.insert(deqA.begin() + 1, 2, 33); //{11,33,33,1,3,5,7,9}
deqA.insert(deqA.begin(), deqB.begin(), deqB.end()); //{2,4,6,8,11,33,33,1,3,5,7,9}
}
void objPlay9()
{
int intarr[10] = { 1, 3, 2, 3, 3, 3, 4, 3, 5, 3 };
//假设 deqInt 包含1, 3, 2, 3, 3, 3, 4, 3, 5, 3,删除容器中等于3的元素
deque<int> deqInt(intarr, intarr + 10);
for (deque<int>::iterator it = deqInt.begin(); it != deqInt.end();) //小括号里不需写 ++it
{
if (*it == 3)
{
it = deqInt.erase(it); //以迭代器为参数,删除元素3,并把数据删除后的下一个元素位置返回给迭代器。
//此时,不执行 ++it;
}
else
{
++it;
}
}
//删除deqInt的所有元素
deqInt.clear(); //容器为空
}
标签:
原文地址:http://www.cnblogs.com/chengsong/p/5080947.html