deque(双端队列)
双端队列可以看成是在队列的基础上进行了扩展,我们知道队列的操作只能是在头尾,并且出队列只能是在头部,入队列只能是在尾部。同时双端队列又是顺序容器,因此可以随机访问每个元素。所以,双端队列综合了队列与序列容器的共同特点。
虽然deque是序列容器,但它与vector内部结构又完全不相同,vector内部是一个简单数组,如果需要更大的空间则重新分配内存,然后拷贝过去。deque内不是动态数组,如果需要需要更大空间,则再分配一块内存,添加到之前的后面,所以deque内部的数据时存储在好几块内存区,而并不是连续的。
头文件:#include
构造函数
// constructors used in the same order as described above:
std::deque<int> first; // empty deque of ints
std::deque<int> second (4,100); // four ints with value 100
std::deque<int> third (second.begin(),second.end()); // iterating through second
std::deque<int> fourth (third); // a copy of third
// the iterator constructor can be used to copy arrays:
int myints[] = {16,2,77,29};
std::deque<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
std::cout << "The contents of fifth are:";
for (std::deque<int>::iterator it = fifth.begin(); it!=fifth.end(); ++it)
std::cout << ' ' << *it;
迭代器
std::deque<int> first; // empty deque of ints
std::deque<int> second(4, 100); // four ints with value 100
deque<int>::iterator it;
it = first.begin();
it = first.end();
容器大小函数
std::deque<int> first; // empty deque of ints
std::deque<int> second(4, 100); // four ints with value 100
cout << second.size() << endl; //deque元素个数
cout << second.empty() << endl; //deque是否为空
second.resize(10); //重新设置大小,这时size()函数返回10,并且原来的值不改变,多于的空间内存初始化为0
second.shrink_to_fit(); //由于deque有预留空间,因此调用这个函数可以压缩占用空间
元素访问
int myints[] = { 16, 2, 77, 29 };
std::deque<int> fifth(myints, myints + sizeof(myints) / sizeof(int));
//同时拥有序列容器与队列的访问方式
cout << fifth[1] << endl;
cout << fifth.at(1) << endl;
cout << fifth.front() << endl;
cout << fifth.back() << endl;
元素修改
int myints[] = { 16, 2, 77, 29 };
std::deque<int> fifth(myints, myints + sizeof(myints) / sizeof(int));
deque<int> second(myints, myints+2);
//插入位置必须是要通过Itertor指定
vector<int> myvector(3, 400);
fifth.insert(fifth.begin(), 300);
fifth.insert(fifth.begin(), myvector.begin(), myvector.end());
fifth.erase(fifth.begin()); //删除第一个元素
fifth.erase(fifth.begin(), fifth.begin() + 3); //删除头三个元素
fifth.swap(second);
fifth.clear(); //清空元素
fifth.emplace(fifth.begin(), 20);
在C++11里面,很多容器都添加了emplace相关的函数,从功能上讲,emplace与insert基本一致,都是向容器中插入元素。但是,调用insert时,我们将元素类型的对象传递给insert,元素的对象被拷贝到容器中,而当我们使用emplace时,我们将参数传递给元素类型的构造函数,emplace使用这些参数在容器管理的内存空间中直接构造元素。所以,两者的主要区别是执行效率上,emplace执行效率更高,但对于大多数程序来讲,这点应该影响不大。