一、deque(双队列)的简单使用
deque<int> d1;
d1.push_back(1);//在尾部放入元素
d1.push_front(2);//在头部放入元素
//遍历
for(deque<int>::iterator it=d1.begin();it!=d1.end();it++)
cout<<*it;
cout<<d1.front()<<endl;//显示头部元素
cout<<d1.back()<<endl;//显示尾部元素
d1.pop_front();//弹出头部元素 ,相当于删除
d1.pop_back(); //弹出尾部元素
//查找某值得下标位置
deque<int>::iterator it=find(d1.begin(),d1.end(),2);
if(it!=d1.end())
{
cout<<distance(d1.begin(),it)<<endl;//distance算出it里起始位置得距离,也就是下标
}
stack(栈)的简单使用
stack<int> s1;
for(int i=0;i<9;i++)
s1.push(i);//往栈中压入元素
while(!s1.empty())//检查栈是否为空
{
cout<<s1.top()<<endl;//显示栈中的元素,这里可以显示说明函数是有返回值的,可以用变量去赋值
s1.pop();//弹出(删除)栈中的元素
}
queue(队列)的简单使用
queue<int> q1;
q1.push(1);
q1.push(2);
q1.push(3);//压入元素
cout<<q1.size()<<endl;//显示队列中元素的个数,其他容器也有此函数
while(!q1.empty())//若队列非空
{
cout<<q1.front()<<endl;//显示对头元素
q1.pop();//弹出元素
}
List容器
1、list是一个双向链表容器,可高效的进行插入删除元素
2、list不支持随机存取元素,所以不支持at.(index)与[]操作符,用迭代器;
基本操作
list<int> l;
for(int i=0;i<10;++i)
l.push_back(i);//从尾部插入元素,也可以从头部插
list<int>::iterator it=l.begin();//只能通过迭代器访问
while(!l.empty())
{
cout<<*it<<endl;
it++;
l.pop_front();//从头部删除元素;
}
插入删除元素
//插入元素
it=l.begin();
l.insert(it,1);//插入的位置在it之前差,即插入元素的位置是it所指向的位置。
//删除元素
it.clear();//清除容器内所有的元素
it.erase(l.begin(),l.end()) ;//删除一个区间的元素,左闭右开
it.erase(it);//删除it指向的位置,返回下一个位置
it.remove(2);//删除容器中等于2的元素。
优先级队列
优先级队列根据值得大小来输入输出,有两种模式:最大值优先级队列和最小值优先级队列。最大值优先级队列值最大的元素先输出,最小值相反。
priority_queue<int> q1;//默认情况下是最大值优先级
priority_queue<int,vector<int>,less<int> > q2;//默认情况下
priority_queue<int,vector<int>,greater<int> > q3;//最小值优先级队列
q1.push(1);//插入元素
q1.push(5);
q1.push(4);
q1.push(2);
while(!q1.empty())
{
cout<<q1.top()<<endl;//显示先出队的元素
q1.pop();//弹出队中的元素
}