您的位置:首页 > 其它

栈,队列,优先队列的使用

2016-04-21 18:56 393 查看
一:优先队列priority_queueempty() 如果队列为空返回真pop() :删除对顶元素push(): 加入一个元素size() :返回优先队列中拥有的元素个数top() :返回优先队列对顶元素在默认的优先队列中,优先级高的先出队。在默认的int型中先出队的为较大的数。使用方法:头文件:#include <queue>声明方式:1、普通方法:priority_queue<int>q;
//通过操作,按照元素从大到小的顺序出队2、结构体声明方式:struct node
{
int x, y;
friend booloperator< (node a, node b)
{
return a.x > b.x; //结构体中,x小的优先级高
}
};或者struct Item
{
int Time,Qnum,Period;///Time是用来存时间的
///优先级比较函数,优先级高的先出队
bool operator< (const Item& a)const {///const必不可少
return Time>a.Time||(Time==a.Time&&Qnum>a.Qnum);//如果Time优先级一样,就按Qnum的优先级出队
}
};priority_queue<node>q;//定义方法
//在该结构中,y为值, x为优先级。
//通过自定义operator<操作符来比较元素中的优先级。
//在重载”<”时,最好不要重载”>”,可能会发生编译错误
============================================================================================================二:STL 中队列的使用(queue)基本操作:push(x) 将x压入队列的末端pop() 弹出队列的第一个元素(队顶元素),注意此函数并不返回任何值front() 返回第一个元素(队顶元素)back() 返回最后被压入的元素(队尾元素)empty() 当队列为空时,返回truesize() 返回队列的长度使用方法:头文件:#include <queue>声明方法:1、普通声明
queue<int>q;2、结构体struct node
{
int x, y;
};
queue<node>q;============================================================================================================三:STL 中栈的使用方法(stack)基本操作:push(x) 将x加入栈中,即入栈操作pop() 出栈操作(删除栈顶),只是出栈,没有返回值top() 返回第一个元素(栈顶元素)size() 返回栈中的元素个数empty() 当栈为空时,返回 true使用方法和队列差不多,其中头文件为:#include <stack>定义方法为:stack<int>s1;//入栈元素为 int 型
stack<string>s2;// 入队元素为string型
stack<node>s3;//入队元素为自定义型============================================================================================================优先队列的例子
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<stdlib.h>
#include<iomanip>
#include<list>
#include <stdio.h>
#include <queue>
using namespace std;
struct node
{
int value;
int id;
friend bool operator <(node a,node b)
{
return a.value<b.value;
}
};
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int n;
priority_queue<node>pq;
int i=0;
while(cin>>n&&n)
{
i++;
node s;
s.id=i;s.value=n;
pq.push(s);
}
while(!pq.empty())
{
node d=pq.top();pq.pop();
cout<<d.id<<" ";
}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: