STL-栈
#include<stdio.h>
#include<stack>
using namespace std;
struct node{
int value;
struct node * next;
};
int main(){
stack<int> s;
s.push(5);
s.push(6);
while(!s.empty()){
int x = s.top();
printf("%d %d\n",x,s.size());
s.pop();
}
stack<struct node>root;
struct node x,y;
x.value = 3;
y.value = 4;
root.push(x);
root.push(y);
while(!root.empty()){
printf("%d %d\n",root.top().value,root.size());
root.pop();
}
return 0;
}
STL-队列
#include<stdio.h>
#include<queue>
using namespace std;
struct node{
int value;
struct node * next;
};
int main(){
queue<struct node>root;
struct node x,y,z;
x.value = 3;
y.value = 4;
z.value = 5;
root.push(x);
root.push(y);
root.push(z);
while(!root.empty()){
struct node front = root.front();
struct node back = root.back();
root.pop();
printf("front:%d\t",front.value);
printf("back:%d\t",back.value);
printf("size:%d\n",root.size());
}
return 0;
}
STL-优先队列
#include<stdio.h>
#include<queue>
#include<vector>
using namespace std;
struct cmp{
bool operator ()(int &a,int &b){
return a>b;//a的优先级小于b的优先级 条件是a<b,因此,这种情况下数值越小,优先级越小 ;a的优先级小于b的优先级 条件是a>b,因此,这种情况下数值越大,优先级越小
}
};
struct node{
int value;
struct node * next;
friend bool operator < (node a, node b){
return a.value > b.value; //同理,a的优先级小于b的优先级,条件是a.value > b.value
}
};
//在该结构中,y为值, x为优先级。
//通过自定义operator<操作符来比较元素中的优先级。
//在重载”<”时,最好不要重载”>”,可能会发生编译错误
int main(){
priority_queue<int>q1;
q1.push(3);
q1.push(1);
q1.push(5);
while(!q1.empty()){
printf("%d %d\n",q1.top(),q1.size());
q1.pop();
}
printf("------\n");
priority_queue<int,vector<int>,cmp>q2;
q2.push(3);
q2.push(1);
q2.push(5);
while(!q2.empty()){
printf("%d %d\n",q2.top(),q2.size());
q2.pop();
}
printf("------\n");
priority_queue<struct node>q3;
struct node x,y,z;
x.value = 2;
y.value = 5;
z.value = 1;
q3.push(x);
q3.push(y);
q3.push(z);
while(!q3.empty()){
struct node p = q3.top();
printf("%d %d\n",p.value,q3.size());
q3.pop();
}
return 0;
}