zltzlt 发表于 2020-2-20 20:21:31

C++ 标准库的栈和队

标准库的栈和队



#include <stack>
#include <iostream>

using namespace std;

int main()
{
    stack<int> s;
    int i = 0;
    for (; i < 10; i++)
      s.push(i);            // 将元素压入栈顶
    cout << s.size() << endl; // 获取栈中元素个数
    while (!s.empty())      // s.empty() 返回栈是否为空
    {
      cout << s.top() << " "; // 输出栈顶元素
      s.pop();                // 弹出栈顶元素
    }
    return 0;
}

运行结果:

10
9 8 7 6 5 4 3 2 1 0



#include <iostream>
#include <queue>
using namespace std;

int main()
{
    int num;
    queue<int> q;

    cout << "========= 队列 =========" << endl;
    cout << "输入数字(输入非数字元素停止):" << endl;

    while (cin >> num)
      q.push(num);

    cout << "获取队列长度:" << q.size() << endl;
    cout << "获取队首元素:" << q.front() << endl;
    cout << "获取队尾元素:" << q.back() << endl;
    q.pop();
    cout << "弹出一个元素后队首元素为:" << q.front() << endl;
    cout << "队列是否为空:" << q.empty() << endl;
    cout << "队列现在的所有元素:" << endl;
    while (!q.empty())
    {
      cout << q.front() << " ";
      q.pop();
    }

    return 0;
}

运行结果:

========= 队列 =========
输入数字(输入非数字元素停止):
1 2 3 4 5 6 7 8 9 10 q
获取队列长度:10
获取队首元素:1
获取队尾元素:10
弹出一个元素后队首元素为:2
队列是否为空:0
队列现在的所有元素:
2 3 4 5 6 7 8 9 10
页: [1]
查看完整版本: C++ 标准库的栈和队