deque是双端队列,在头部和尾部都可以添加或删除数据,下面我们来看它的一些基本使用情况,首先来学习创建和初始化操作。
deque的创建和初始化有多种方式 ,不仅可以直接初始化,还可以使用其他容器进行初始化,也可以使用assign进行设置固定容量和值,下面来看下具体的代码:
#include <deque>
#include <iostream>
using namespace std;
void createDequeInit()
{
//1.创建空双端队列deque1
deque<int> deque1;
cout << "deque1.isEmpty = " << deque1.empty() << " deque1.size = " << deque1.size() << " deque1.max_size = " << deque1.max_size()<< endl;
//2.创建deque2有2个元素,值为随机值
deque<int> deque2(2);
cout << "deque2.isEmpty = " << deque2.empty() << " deque2.size = " << deque2.size() << " deque2.max_size = " << deque2.max_size()<< endl;
cout << "deque2的值为:" << endl;
for(auto &val: deque2)
{
cout << val << "\t";
}
cout << endl;
//3.创建deque3有3个元素,分别为11, 12, 13
deque<int> deque3 = {11, 12, 13};
cout << "deque3.isEmpty = " << deque3.empty() << " deque3.size = " << deque3.size() << " deque3.max_size = " << deque3.max_size()<< endl;
cout << "deque3的值为:" << endl;
for(auto &val: deque3)
{
cout << val << "\t";
}
cout << endl;
//4.创建deque4,用deque3赋值
deque<int> deque4 = deque3;
//deque<int> deque4(deque3);//这两种方法都可以
cout << "deque4.isEmpty = " << deque4.empty() << " deque4.size = " << deque4.size() << " deque4.max_size = " << deque4.max_size()<< endl;
cout << "deque4的值为:" << endl;
for(auto &val: deque4)
{
cout << val << "\t";
}
cout << endl;
//5.创建deque5用assign进行赋值
deque<int> deque5;
deque5.assign({14, 15, 16, 17});
cout << "deque5的值为:" << endl;
for(auto &val: deque5)
{
cout << val << "\t";
}
cout << endl;
//6.创建deque6用deque4进行初始化
deque<int> deque6(deque4.begin(), deque4.end());
cout << "deque6的值为:" << endl;
for(auto &val: deque6)
{
cout << val << "\t";
}
cout << endl;
cout << "deque6.size = " << deque6.size() << " deque6.max_size = " << deque6.max_size() << endl;
//7.创建deque7用assign设定容器大小和初始值
deque<int> deque7;
deque7.assign(5, 18);//deque7有5个元素,每个元素为18
cout << "deque7的值为:" << endl;
for(auto &val: deque7)
{
cout << val << "\t";
}
cout << endl;
cout << "deque7.size = " << deque7.size() << " deque7.max_size = " << deque7.max_size() << endl;
}
int main()
{
createDequeInit();
cout << endl;
cout << "Hello World!" << endl;
return 0;
}
运行结果: