deque容器类型

来源:互联网 发布:网络工程师不是程序员 编辑:程序博客网 时间:2024/05/18 02:06

 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 stringsdeque<string> coll;//insert several elementscoll.assign(3, string("string"));coll.push_back("last string");coll.push_front("first string");//print elements separated by newlinescopy(coll.begin(), coll.end(), ostream_iterator<string>(cout, "\n"));cout<<endl;//remove the first and last elementcoll.pop_front();coll.pop_back();//print elements separated by newlinescopy(coll.begin(), coll.end(), ostream_iterator<string>(cout, "\n"));cout<<endl;//insert "anthor" into every element but the firstfor (int i = 1; i < coll.size(); ++ i) {coll[i] = "anthor " + coll[i];}//change size to four elementcoll.resize(4, "resized sring");//print elements separated by newlinescopy(coll.begin(), coll.end(), ostream_iterator<string>(cout, "\n"));cout<<endl;return 0;}
运行结果:





原创粉丝点击