栈:后进先出(last in first out LIFO)
头文件 stack < stack >
stack < int > s;
栈的基本操作:
- s.empty() 如果栈为空返回true,否则返回false
- s.size() 返回栈中元素的个数
- s.pop() 删除栈顶元素但不返回其值
- s.top() 返回栈顶的元素,但不删除该元素
- s.push() 在栈顶压入新元素
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<int>s;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int a;
cin>>a;
s.push(a);
}
while(!s.empty()) //s.empty() 空返回true 否则false
{
cout<<s.top();
s.pop();
cout<<endl;
}
return 0;
}
队列:先进先出 (Frist In Frist Out,FIFO)
头文件 #include< queue >
queue< int >q;
队列的基本操作:
- q.empty() 如果队列为空返回true,否则返回false
- q.size() 返回队列中元素的个数
- q.pop() 删除队列首元素但不返回其值
- q.front() 返回队首元素的值,但不删除该元素q
- .push() 在队尾压入新元素
- q.back() 返回队列尾元素的值,但不删除该元素
#include<iostream>
#include<queue>
using namespace std;
int main()
{
queue<string>s;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
string a;
cin>>a;
s.push(a);
}
while(!s.empty())
{
cout<<s.front()<<endl;
s.pop();
}
return 0;
}
优先队列:默认为越小的整数优先级越低(从大到小排序)
头文件:#include< queue >
定义:priority_queue< int >s1; (默认越小的整数优先级越低)
cmp设置越大的整数优先级越低(从小到大排序)
两种方法:
1.直接声明:
priority_queue<int ,vector<int>,greater<int> > s2;
2.运用结构体重载
struct cmp{
bool operator() (const int a,const int b) const{
return a>b;
}
};
priority_queue<int,vector<int>,cmp>s;
基本操作:
- q.size();//返回q里元素个数
- q.empty();//返回q是否为空,空则返回1,否则返回0
- q.push(k);//在q的末尾插入k
- q.pop();//删掉q的第一个元素
- q.top();//返回q的第一个元素
代价:
#include<iostream>
#include<queue>
using namespace std;
struct cmp{
bool operator() (const int a,const int b) const{
return a>b;
}
};
int main()
{
priority_queue<int>s1;
priority_queue<int ,vector<int>,greater<int> > s2;
priority_queue<int,vector<int>,cmp>s;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int a;
cin>>a;
s.push(a);
}
while(!s.empty())
{
cout<<s.top()<<endl;
s.pop();
}
return 0;
} ```