std::stack
类是一种容器适配器,它给予程序员栈的功能——特别是 FILO(先进后出)数据结构。该类模板用处为底层容器的包装器——只提供特定函数集合。栈从被称作栈顶的容器尾部推弹元素。
operator= | 赋值给容器适配器 (公开成员函数) |
元素访问 | |
top | 访问栈顶元素 (公开成员函数) |
容量 | |
empty | 检查容器适配器是否为空 (公开成员函数) |
size | 返回元素数 (公开成员函数) |
修改器 | |
push | 向栈顶插入元素 (公开成员函数) |
push_range (C++23) | 在栈顶插入元素范围 (公开成员函数) |
emplace (C++11) | 在顶部原位构造元素 (公开成员函数) |
pop | 移除栈顶元素 (公开成员函数) |
swap (C++11) | 交换内容 (公开成员函数) |
operator==operator!=operator<operator<=operator>operator>=operator<=> | 按照字典顺序比较两个 stack 的值 (函数模板) |
示例代码
#include <cassert>
#include <iostream>
#include <stack>
int main()
{
//1.容量函数empty, size
std::stack<int> sta1;
std::cout << "sta1.empty()==========" << sta1.empty() << std::endl;
std::cout << "sta1.size()===========" << sta1.size() << std::endl;
//修改器:push, emplace, pop, swap
std::stack<int> sta2;
sta2.push(0); //向除队列尾部插入0
sta2.push(1); //sta2 = 0 1
sta2.push(2); //sta2 = 0 1 2
sta2.emplace(3); //sta2 = 0 1 2 3 在尾部原位构造元素
std::cout << "sta2.empty()==========" << sta2.empty() << std::endl;
std::cout << "sta2.size()===========" << sta2.size() << std::endl;
sta2.pop(); //移除首个元素 , 0
std::cout << "sta2.size()===========" << sta2.size() << std::endl;
sta1.swap(sta2); //交接内容
std::cout << "sta1.empty()==========" << sta1.empty() << std::endl;
std::cout << "sta1.size()===========" << sta1.size() << std::endl;
std::cout << "sta2.empty()==========" << sta2.empty() << std::endl;
std::cout << "sta2.size()===========" << sta2.size() << std::endl;
//元素访问 top
int top = sta1.top(); //访问栈顶元素
std::cout << "sta1.top()==========" << top << std::endl;
std::stack<int> sta3;
bool b1 = (sta1 == sta3);
bool b2 = (sta1 != sta3);
bool b3 = (sta1 < sta3);
bool b4 = (sta1 <= sta3);
bool b5 = (sta1 > sta3);
bool b6 = (sta1 >= sta3);
std::cout << "(sta1 == sta3)========" << b1 << std::endl;
std::cout << "(sta1 != sta3)========" << b2 << std::endl;
std::cout << "(sta1 < sta3)=========" << b3 << std::endl;
std::cout << "(sta1 <= sta3)========" << b4 << std::endl;
std::cout << "(sta1 > sta3)=========" << b5 << std::endl;
std::cout << "(sta1 >= sta3)========" << b6 << std::endl;
std::cout << "sta3.empty()==========" << sta3.empty() << std::endl;
std::cout << "sta3.size()===========" << sta3.size() << std::endl;
sta3 = sta1; //赋值
std::cout << "sta3.empty()==========" << sta3.empty() << std::endl;
std::cout << "sta3.size()===========" << sta3.size() << std::endl;
assert(sta1.size() == 3);
return 0;
}
参考:
https://zh.cppreference.com/w/cpp/container/stack
https://cplusplus.com/reference/stack/stack/