您的位置:首页 > 编程语言 > C语言/C++

C++ STL学习笔记三 deque双端队列容器

2010-04-16 21:33 796 查看
/*
*
********************************************
* deque双端队列容器的基础说明:
********************************************
*
*
* 可进行随机访问,在**头部和尾端**插入、删除元素,时间复杂度为O(1)
* Random Access Container Back Insertion Sequence Front Insertion Sequence
*
************************************************************************************
* 当考虑容器元素的内存分配策略和操作的性能时,deque较vector更具优势 *
* map管理块,块中包含一组数据,内存分配更细致(以块为单位,使用二级的MAP进行管理) *
************************************************************************************
*
* 使用deque必须使用宏语句#include <deque>
*
**************************************************************************************
*
* 创建deque对象:
* 1.deque<int> a;
* 2.deque<int> a(10); //具有10个元素的对象a,每个元素默认值为0
* 3.deque<char> a(5,'k');
* 4.deque<char> b(a); //deque<char> c(a.begin(),a.end())
*
**************************************************************************************
*
* 初始化赋值
* void push_back(const T& value)
*
**************************************************************************************
*
* 遍历访问
* reference operator[](size_type n)
* iterator begin()
* iterator end()
*
**************************************************************************************
*
* 常用函数
*
* bool empty();
* size_type size();size_type max_size(); //无size_type capacity();reverse();
* reference front();reference back();
* void pop_front();void push_front(); //相较vector增加部分
* void pop_back();void push_back();
* void clear();
* //还有些函数直接见代码如erase();
*
*
*
********************************************
* Author: cumirror
* Email: tongjinooo@163.com
********************************************
*
*/

#include <iostream>
#include <deque>

int main()
{
using namespace std;
deque<int> a(10,5);

// 数组方式
cout<<"数组方式访问:"<<endl;
a[0]=100;
for(int s=0;s<a.size();s++){
cout<<a[s]<<endl;
}

// 迭代器方式
cout<<"迭代器方式访问:"<<endl;
deque<int>::iterator i,iend;
i=a.begin();
iend=a.end();
*i=101;
for(deque<int>::iterator j=i;j!=iend;j++){
cout<<*j<<endl;
}

//注意插入删除时迭代器的失效问题,偷个懒,大家可以看下面的网页,里面有说明但没介绍原因,其实这与各个容器是如何实现的有很大关系,若想深究可看《STL源码剖析》
//http://blog.csdn.net/jokenchang2000/archive/2008/07/01/2603485.aspx
cout<<"插入"<<endl;
a.insert(a.begin(),102);

// 删除时注意,它是一个半闭区间
// 也支持 erase(iterator pos)单个元素的删除
cout<<"删除"<<endl;
a.erase(a.begin()+4,a.begin()+6);
for(deque<int>::iterator k=a.begin();k!=a.end();k++){
cout<<*k<<endl;
}

// 头部插入
a.push_front(999);

// 反向遍历访问
cout<<"反向访问"<<endl;
deque<int>::reverse_iterator ri;
for(ri=a.rbegin();ri!=a.rend();ri++){
cout<<*ri<<endl;
}

deque<int> b;
b.push_back(4);
b.push_back(5);
b.push_front(3);
b.push_front(2);
cout<<"互换"<<endl;
b.swap(a);
for(int l=0;l<a.size();l++){
cout<<a[l]<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: