STL中序列容器之deque

以下学习一下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;
}

输出为:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值