美文网首页
C++(STL) 栈(stack)和队列(queue)(转载)

C++(STL) 栈(stack)和队列(queue)(转载)

作者: Minority | 来源:发表于2020-02-09 14:50 被阅读0次

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

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

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

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

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

//栈操作举例:
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
 
void main()
{
    stack<int> s;
    int num;
 
    cout<<"------Test for Stack-------"<<endl;
    cout<<"Input number:"<<endl;
    
    while(cin>>num)
    {
        s.push(num);
    }
 
    cout<<"The Stack has "<<s.size()<<" numbers.They are:"<<endl;
    while(!s.empty())
    {
        cout<<s.top()<<" ";
        s.pop();
    }
    cout<<"\nNow the size is "<<s.size()<<endl;
    system("Pause");
}

结果截图:


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

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

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

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

//队列操作举例
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
 
void main()
{
    queue<int> q;
    int num;
 
    cout<<"------Test for Queue-------"<<endl;
    cout<<"Input number:"<<endl;
    while(cin>>num)
    {
        q.push(num);
    }
    cout<<"Now the Queue has "<<q.size()<<" numbers."<<endl;
    cout<<"The first is "<<q.front()<<endl;
    cout<<"The last is "<<q.back()<<endl;
    cout<<"All numbers:"<<endl;
    while(!q.empty())
    {
        cout<<q.front()<<" ";
        q.pop();
    }
    cout<<"Now the Queue has "<<q.size()<<" numbers."<<endl;
    system("Pause");
 
 
}

结果截图:


转载自:https://blog.csdn.net/livecoldsun/article/details/25011413

相关文章

网友评论

      本文标题:C++(STL) 栈(stack)和队列(queue)(转载)

      本文链接:https://www.haomeiwen.com/subject/mdagxhtx.html