1.有关函数的作用
stack<type> s | 定义一个参数类型为 type 的栈 |
s.push() | 压栈,无返回值 |
s.emplace() | 压栈,无返回值(与push的区别下面细说) |
s.pop() | 栈顶元素出栈,不返回元素,无返回值 |
s.top() | 返回栈顶元素,该元素不出栈 |
s.empty() | 判断栈是否为空,是返回 true |
s.size() | 返回栈中元素数量 |
2、举例
#include <stack>
#include <string>
#include<iostream>
using namespace std;
int main()
{
stack<string> test_stack;
test_stack.push("you~ "); // 向栈中压入元素(pop)
test_stack.push("meet "); // 向栈中压入元素(pop)
test_stack.push("to "); // 向栈中压入元素(pop)
test_stack.push("nice "); // 向栈中压入元素(pop)
cout << "size of test_stack: " << test_stack.size() << endl; // 获取栈内元素数量
while (!test_stack.empty()) // 栈是否为空,是:true
{
string temp = test_stack.top(); // 返回栈顶元素,该元素不出栈
cout << temp;
test_stack.pop(); // 栈顶元素出栈,不返回元素
}
system("pause");
return 0;
}
实际上stack中元素位置排序(由底层往上):nice -> to ->meet -> you~
因此输出结果:

