deque采用动态数组来管理元素,提供随机存储,有着和vector几乎一模一样的接口。不同的是deque提供的动态数组头尾都开放,因此能在头尾两端进行快速的安插和删除。
使用deque时必须包含头文件<deque>
#include <deque>
其中deque型别定义于namespace std中,是个class template:
namespace std {
template<class T,
class Allocator = allocator<T> >
class deque;
}
适用于以下情形:
①需要在两端安插和移除元素
②无需引用容器内的元素
③要求容器释放不再使用的元素。(不过标准规格上并没有保证这一点)
实践应用:
#include <iostream>
#include <deque>
#include <string>
#include <algorithm>
using namespace std;
int main(int argc, char **argv)
{
//create empty deque of strings
deque<string> coll;
//insert several elements
coll.assign(3, string("string"));
coll.push_back("last string");
coll.push_front("first string");
//print elements separated by newlines
copy(coll.begin(), coll.end(), ostream_iterator<string>(cout, "\n"));
cout<<endl;
//remove the first and last element
coll.pop_front();
coll.pop_back();
//print elements separated by newlines
copy(coll.begin(), coll.end(), ostream_iterator<string>(cout, "\n"));
cout<<endl;
//insert "anthor" into every element but the first
for (int i = 1; i < coll.size(); ++ i) {
coll[i] = "anthor " + coll[i];
}
//change size to four element
coll.resize(4, "resized sring");
//print elements separated by newlines
copy(coll.begin(), coll.end(), ostream_iterator<string>(cout, "\n"));
cout<<endl;
return 0;
}
运行结果: