您的位置:首页 > 产品设计 > UI/UE

STL中序列容器之deque

2013-11-18 22:09 288 查看
以下学习一下STL中另一种序列容器——deque。

deque表示double-ended queue,即双向队列,deque是通过作为动态数组的方式实现的,这样可以在两端插入元素。因此,deque可以在任何一个方向进行扩展。同时可以在中间插入元素。在开头或结尾处插入元素非常的快,然而在中间插入元素将会比较耗时间,因此需要移动队列中的元素。

定义deque容器的类名为deque。类deque的定义以及deque对象的各种操作函数的实现包含在头文件<deque>中,因此,在程序中使用deque时,程序中必须包含如下语句:

#include <deque>


类deque中包含好几个构造器,因此,当声明一个deque对象时,可以通过各种方式进行初始化。如下表中提供的方式:



除了之前介绍的所有序列容器通用的操作意外,下表还描述了用来管理deque容器的元素的操作。各个语句展示了如何使用某一个特定的函数,其中假设deq是一个deque容器



下例展示了如何在程序中使用deque。

#include <iostream>
#include <deque>
#include <algorithm>
#include <iterator>

using namespace std;

int main()
{
deque<int> intDeq;
ostream_iterator<int> screen(cout, " ");

intDeq.push_back(13);
intDeq.push_back(75);
intDeq.push_back(28);
intDeq.push_back(35);

cout << "intDeq: ";
copy(intDeq.begin(), intDeq.end(), screen);
cout << endl;

intDeq.push_front(0);
intDeq.push_back(100);

cout << "After adding two more "
<< "elements, one at the front " << endl
<< "	and one at the back, intDeq: ";

copy(intDeq.begin(), intDeq.end(), screen);
cout << endl;

intDeq.pop_front();
intDeq.pop_front();

cout << "After removing the first "
<< "two elements, " << endl
<< "	intDeq: ";
copy(intDeq.begin(), intDeq.end(), screen);
cout << endl;

intDeq.pop_back();
intDeq.pop_back();

cout << "After removing the last "
<< "two elements, " << endl
<< "	intDeq: ";
copy(intDeq.begin(), intDeq.end(), screen);
cout << endl;

deque<int>::iterator deqIt;
deqIt = intDeq.begin();
++deqIt;
intDeq.insert(deqIt, 666);

cout << "After inserting 666, "
<< "intDeq: ";
copy(intDeq.begin(), intDeq.end(), screen);
cout << endl;

intDeq.assign(2, 45);

cout << "After assigning two "
<< "copies of 45, intDeq: ";
copy(intDeq.begin(), intDeq.end(), screen);
cout << endl;

intDeq.push_front(-10);
intDeq.push_front(-999);

cout << "After inserting two "
<< "elements, one at the front " << endl
<< "	and one at the back, intDeq: ";
copy(intDeq.begin(), intDeq.end(), screen);
cout << endl;

return 0;
}


输出为:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: