|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
标准库的栈和队
栈
- #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;
- }
复制代码
运行结果:
队
- #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
复制代码 |
|