原创博客,转载请注明出处
deque是list和vector折中的一个容器
它支持随机访问,支持在中间插入和删除元素。
deque的内存模型是多个连续的内存块,并在一个映射结构中保存了对这些块的顺序以及内容的跟踪
例如一个deque
第一块(内存相邻):1 2 3 ->(块间指针) 第二块(内存相邻) 4 5 6-> ....
一、deque的特点
- 支持双端插入删除
- 不支持对容量和内存机制的控制
- 随机访问的效率没有vector高,插入删除元素效率没有list高
- 除了在首位插入元素不会使迭代器,指针引用失效,其他都会使指针迭代器失效
- 内存优化比vector较好,因为不需要每次增加内存的时候都复制所有元素
使用deque的情形
1、在容器两端插入删除元素
2、不引用容器内元素
3、要求容器删除不再使用的元素
就是一句话:性能介于vector和list之间
二 、常用函数
deque d;//默认构造函数,空队列
deque d(d1);//用d1构造d
deque d2(n,elem);//构造n个elem元素的队列
d.empty();//队列是否为空
d.clear();//队列清空
d.size()//队列当前元素个数
d.front();d.back();//第一个和最后一个元素
d.begin();d.end();//第一个元素迭代器位置,最后一个元素后一起迭代器位置
d.rbegin();d.rend();//最后一个元素迭代器位置,第一个元素迭代器下一个位置
d.at(index);//index处的元素(随机访问)
d[index]//随机访问
d.insert(pos,elem)//在pos处插入elem pos为迭代器
d.push_back(elem);d,pop_back();//末尾添加一个元素和删除一个元素
d.push_front();d.pop_back();//队列头添加和删除一个元素
d.erase(pos);//删除pos处的元素,返回下一个元素的迭代器位置
d.erase(begin,end);//删除一个区间
d.insert(pos,begin,end);//在pos处插入begin到end处的元素
d.swap(d1);//交换两个deque
#include "stdafx.h"
#include <iostream>
#include <string>
#include <deque>
#include <algorithm>
#include <iterator>
using namespace std;
string backdata[]={"hello","hwc"};
typedef deque<string> hwcdeque;
int _tmain(int argc, _TCHAR* argv[])
{
hwcdeque firstdeque;
copy(backdata,backdata+2,back_insert_iterator<hwcdeque>(firstdeque));
copy(firstdeque.begin(),firstdeque.end(),ostream_iterator<string>(cout," "));
cout<<endl;
firstdeque.push_back("how");
firstdeque.push_back("are");
firstdeque.push_back("you");
hwcdeque::iterator firstIt = firstdeque.begin();
while (firstIt != firstdeque.end())
{
cout<<(*firstIt)<<" ";
firstIt++;
}
cout<<endl;
firstdeque.push_front("Information:");//Information: hello hwc how are you
for (unsigned int index = 0;index < firstdeque.size();index++)
{
cout<<firstdeque.at(index)<<" ";
//cout<<firstdeque[index]<<" ";
}
cout<<endl;
firstIt = find(firstdeque.begin(),firstdeque.end(),"how");
if (firstIt != firstdeque.end())
{
firstdeque.insert(firstIt+1,"old");//Information: hello hwc how old are you
}
copy(firstdeque.begin(),firstdeque.end(),ostream_iterator<string>(cout," "));
cout<<endl;
firstIt = firstdeque.begin();
firstIt = firstdeque.erase(firstIt);//Erase "Information:"
firstIt = firstdeque.erase(firstIt);//Erase "hello"
firstIt = firstIt + 2;
firstIt = firstdeque.erase(firstIt);//Erase "old"
copy(firstdeque.begin(),firstdeque.end(),ostream_iterator<string>(cout," "));
cout<<endl;
cout<<"Current size:"<<firstdeque.size()<<endl;
}
运行结果
最后,强烈建议入门的同学不仅仅要学会STL中的容器,也要学会迭代器和算法,这样才能掌握好STL的精髓。
本文深入探讨了deque容器的特性和使用方法,包括其内存模型、支持的功能及应用场景。详细介绍了deque的常用函数,并通过示例展示了如何在实际编程中应用deque,特别强调了与vector和list的区别。
1万+

被折叠的 条评论
为什么被折叠?



