Deques
容器deque和vector非常相似。也采用dynamic array来管理元素,提供随机存取。不同的是deque的dynamic array头尾都开放,因此能在头尾进行快速插入和删除。
deuqe头文件<deque>
deque类型是定义于命名空间std内的一个class template:
namespace std{
template<class T, class Allocator = allocator<T> >
class deque;
}
Deque的能力
与vectors相比,deques功能上的不同处在于:
l 两端都能快速插入和删除元素。
l 存取元素时,deque的内部会多一个间接过程,所以存取和迭代器的动作会稍稍慢一些。
l 迭代器需要在不同区域间跳转,所以必须是特殊的智能指针。
l deque可以内含更多元素,因为它使用不止一块内存。因此deque的max_size()可能更大。
l deque不支持对容量和内存重分配时机的控制。特别要注意的是,除了头尾,在任何地方插入或删除元素,都会导致pointers等失效。
l deque的内存块不再被使用时,会被释放。deque的内存大小是可缩减的。不过,是不是怎么做,以及究竟怎么做,由实现版本定义。
如果是一下情形,最好采用deque:
l 你需要在两端插入和删除元素(这是deque的拿手好戏)。
l 无需引用(refer to)容器内的元素。
l 要求容器释放不再使用的元素(不过,标准并没有保证这一点)。
deques的各项操作只在以下数点和vectors不用:
1.deques不提供容量操作(capacity()和reserve())。
2.deque直接提供函数,用以完成头部元素的插入和删除。
异常处理(Exception Handling)
原则上deque提供的异常处理和vectors提供的一样。新增的操作函数push_front()和pop_front分别对应与push_back()和pop_back():
l 如果以push_back()或push_front()插入元素时发生异常,则该操作不带来任何效应。
l pop_back()和pop_front()不会抛出任何异常。
Deques运用示例
#include <iostream>
#include <deque>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
deque<string> coll;
coll.assign(3, string("string") );
coll.push_back("last string");
coll.push_front("first string");
copy( coll.begin(), coll.end(),
ostream_iterator<string>(cout,"/n") );
cout << endl;
coll.pop_front();
coll.pop_back();
for(int i=1; i<coll.size(); ++i ) {
coll[i] = "another " + coll[i];
}
coll.resize(4, "resized string");
copy( coll.begin(), coll.end(),
ostream_iterator<string>(cout,"/n") );
}