#include 赞 踩 双端队列的基本操作 输出 Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。
C++ 双端队列_c++中双端队列的操作
pop_back() //尾部删除
pop_front() //头部删除
push_back() //尾部插入
push_front() //头部插入
insert() //指定位置插入
erase(); //指定位置删除
clear() //清空队列
#include "deque.h"
#include <deque>
#include <iostream>
using namespace std;
/*
基本函数
pop_back()
pop_front()
push_back()
push_front()
insert()
erase();
clear()
*/
//使用push_back()方法从尾部插入元素,会不断扩张队列。
void tail_insert()
{
deque<int>q;
for(int i = 0;i<5;i++)
{
q.push_back(i);
}
for(int i = 0;i<5;i++)
{
cout<<q[i]<<" ";
}
cout<<endl;
}
//从头部插入元素,也会扩张队列。
void front_insert()
{
deque<int>q;
q.push_back(1);
q.push_back(2);
q.push_back(3);
q.push_front(10); //相当于q.insert(q.begin()+1,10);
q.push_front(20); //相当于q.insert(q.begin()+2,10);
for(int i = 0;i<q.size();i++)
{
cout<<q[i]<<" ";
}
cout<<endl;
}
void deque_traverse()
{
deque<int>q;
q.push_back(1);
q.push_back(2);
q.push_back(3);
q.push_front(10); //相当于q.insert(q.begin()+1,10);
q.push_front(20); //相当于q.insert(q.begin()+2,10);
//顺序遍历
deque<int>::iterator it;
for(it =q.begin();it!= q.end();it++ )
{
cout<<*it<<" ";
}
cout<<endl;
//逆序遍历
deque<int>::reverse_iterator rit;
for(rit =q.rbegin();rit != q.rend();rit++)
{
cout<<*rit<<" ";
}
cout<<endl;
}
//可以从双端队列的手部,尾部,中部删除元素,并可以清空双端队列容器
void control_deque()
{
deque<int>q;
q.push_back(1);
q.push_back(2);
q.push_back(3);
q.push_front(10); //相当于q.insert(q.begin()+1,10);
q.push_front(20); //相当于q.insert(q.begin()+2,10);
cout<<" control_deque():";
deque<int>::iterator it;
for(it =q.begin();it!= q.end();it++ )
{
cout<<*it<<" ";
}
cout<<endl;
//删除队尾元素
q.pop_back();
cout<<" pop_back():";
for(it =q.begin();it!= q.end();it++ )
{
cout<<*it<<" ";
}
cout<<endl;
//删除队首元素
q.pop_front();
cout<<" pop_front():";
for(it =q.begin();it!= q.end();it++ )
{
cout<<*it<<" ";
}
cout<<endl;
//删除队列中下标为2的位置元素 参数为指针
q.erase(q.begin()+2);
cout<<" erase():";
for(it =q.begin();it!= q.end();it++ )
{
cout<<*it<<" ";
}
cout<<endl;
//在下标为1处添加新元素8
q.insert(q.begin()+1,8);
cout<<" insert():";
for(it =q.begin();it!= q.end();it++ )
{
cout<<*it<<" ";
}
cout<<endl;
//清空队列
q.clear();
cout<<" clear():";
cout<<" size():"<<q.size();
cout<<endl;
}
void deque_test()
{
tail_insert();
front_insert();
deque_traverse();
control_deque();
}
int main()
{
deque_test();
return 0;
}
0 1 2 3 4
20 10 1 2 3
20 10 1 2 3
3 2 1 10 20
control_deque():20 10 1 2 3
pop_back():20 10 1 2
pop_front():10 1 2
erase():10 1
insert():10 8 1
clear(): size():0