c++中栈和队列基础

转自 ~

在C++标准库(STL)中,实现了栈和队列,方便使用,并提供了若干方法。以下作简要介绍。

1、栈(stack)说明及举例:

使用栈,要先包含头文件 : #include<stack>

定义栈,以如下形式实现: stack<Type> s; 其中Type为数据类型(如 int,float,char等)。

栈的主要操作:

  1. s.push(item);       //将item压入栈顶  
  2. s.pop();            //删除栈顶的元素,但不会返回  
  3. s.top();            //返回栈顶的元素,但不会删除  
  4. s.size();           //返回栈中元素的个数  
  5. s.empty();          //检查栈是否为空,如果为空返回true,否则返回false   


栈操作举例:

  1. #include<iostream>  
  2. #include<stack>  
  3. #include<queue>  
  4. using namespace std;  
  5.   
  6. void main()  
  7. {  
  8.     stack<int> s;  
  9.     int num;  
  10.   
  11.     cout<<"------Test for Stack-------"<<endl;  
  12.     cout<<"Input number:"<<endl;  
  13.       
  14.     while(cin>>num)  
  15.     {  
  16.         s.push(num);  
  17.     }  
  18.   
  19.     cout<<"The Stack has "<<s.size()<<" numbers.They are:"<<endl;  
  20.     while(!s.empty())  
  21.     {  
  22.         cout<<s.top()<<" ";  
  23.         s.pop();  
  24.     }  
  25.     cout<<"\nNow the size is "<<s.size()<<endl;  
  26.     system("Pause");  
  27. }  


结果截图:

2、队列(queue)说明及举例:

使用队列,要先包含头文件 : #include<queue>

定义队列,以如下形式实现: queue<Type> q; 其中Type为数据类型(如 int,float,char等)。

队列的主要操作:

  1. q.push(item)           //将item压入队列尾部  
  2. q.pop()                //删除队首元素,但不返回  
  3. q.front()              //返回队首元素,但不删除  
  4. q.back()               //返回队尾元素,但不删除  
  5. q.size()               //返回队列中元素的个数  
  6. q.empty()              //检查队列是否为空,如果为空返回true,否则返回false  


队列操作举例

  1. #include<iostream>  
  2. #include<stack>  
  3. #include<queue>  
  4. using namespace std;  
  5.   
  6. void main()  
  7. {  
  8.     queue<int> q;  
  9.     int num;  
  10.   
  11.     cout<<"------Test for Queue-------"<<endl;  
  12.     cout<<"Input number:"<<endl;  
  13.     while(cin>>num)  
  14.     {  
  15.         q.push(num);  
  16.     }  
  17.     cout<<"Now the Queue has "<<q.size()<<" numbers."<<endl;  
  18.     cout<<"The first is "<<q.front()<<endl;  
  19.     cout<<"The last is "<<q.back()<<endl;  
  20.     cout<<"All numbers:"<<endl;  
  21.     while(!q.empty())  
  22.     {  
  23.         cout<<q.front()<<" ";  
  24.         q.pop();  
  25.     }  
  26.     cout<<"Now the Queue has "<<q.size()<<" numbers."<<endl;  
  27.     system("Pause");  
  28.   
  29.   
  30. }  


结果截图:

优先队列

Priority_queue<> q;

对队列进行排序

按照优先级的序列出 优先级是自己定义的

队列函数中的front改成top

Struct s{

Int x,y;

Friend bool opeator < (s a,s b)

{

Return a.y<b.y;

}

}

从大到小排 用小于号

 

猜你喜欢

转载自blog.csdn.net/sinat_39654987/article/details/81221014