请注意,本文尚未完成!您可以通过编辑此文档页面来提供帮助。
Stack 类参考
概述
- 简化
- 详细
template< class T, /* ... */ >
class stack;
template<
class T,
class Container = std::deque<T>
>
class stack;
Stack 是一个容器适配器 - 它通过提供新的接口来适配容器。
新接口是一个 LIFO(Last In First Out,后进先出)数据结构。这意味着最后压入的元素是第一个被访问的元素(就像一叠盘子 - 最后压在顶部的盘子是第一个被取走的)。
栈的专业定义
std::stack
类是一个容器适配器,它为程序员提供了栈的功能——特别是 LIFO(后进先出)数据结构。
类模板充当底层容器的包装器——只提供一组特定的函数。栈从底层容器的末尾(称为栈顶)压入和弹出元素。
std::stack
定义于 | 队列 |
模板参数
公共 | T | 存储元素的类型。 如果T 不是 Container::value_type ,则行为未定义。 (自 C++17 起) |
公共 | 容器 | 用于存储元素的底层容器类型。默认为 容器必须满足 SequenceContainer
标准容器 |
类型名称
公共 | 容器类型 | 容器 |
公共 | value_type | Container::value_type |
公共 | size_type | Container::size_type |
公共 | reference | Container::reference |
公共 | const_reference | Container::const_reference |
成员函数
公共 | (构造函数) | 构造一个 |
公共 | (析构函数) | 销毁一个 |
公共 | operator= | 将一个 |
元素访问
公共 | top | 访问顶部(最后压入)的元素 |
容量
公共 | empty | 如果栈为空,则返回 |
公共 | size | 返回栈中的元素数量。 |
修饰符
公共 | push | 在末尾插入一个新元素 |
公共 | emplace (C++11 起) | 在末尾就地构造一个新元素 |
公共 | pop | 移除第一个压入的元素(通过 |
公共 | swap (自 C++11 起) | 交换两个栈 |
成员对象
保护 | Container c | 底层容器。默认为 |
非成员函数
公共 | operator== operator!= operator< operator> operator<= operator>= operator<=> (C++20) | 按字典顺序比较栈中的值。 |
公共 | std::swap (std::stack) | std::swap 算法的重载。 |
辅助类
公共 | std::uses_allocator (std::stack) | 特化 |
推导指南 (C++17 起)
点击展开
// (1)
template< class Container >
stack( Container )
-> stack<typename Container::value_type, Container>;
// (2) (since C++23)
template< class Container, class Alloc >
stack( Container, Alloc )
-> stack<typename Container::value_type, Container>;
(1)
和(2)
允许从底层容器类型推导
(2)
使用 std::deque<typename std::iterator_traits<InputIt>::value_type>
作为底层容器类型(参见 (4)
)
// (3)
template< class Container, class Alloc >
stack( Container, Alloc )
-> stack<typename Container::value_type, Container>;
// (4) (since C++23)
template< class InputIt, class Alloc >
stack( InputIt, InputIt, Alloc )
-> stack<typename std::iterator_traits<InputIt>::value_type,
std::deque<typename std::iterator_traits<InputIt>::value_type, Alloc>>;
与
(1)
和(2)
相同,只是提供了分配器
重载决议
为了使任何推导指南参与重载决议,必须满足以下要求
InputIt
满足LegacyInputIterator
Container
不满足Allocator
- 对于
(3)
(直到 C++23) 和(4)
(自 C++23 起),Alloc
满足Allocator
- 如果
Container
和Alloc
都存在,则std::uses_allocator_v<Container, Alloc>
为真。
库确定类型不满足 LegacyInputIterator
的程度是未指定的,但至少
- 整型不符合输入迭代器的条件。
同样,它确定类型不满足 Allocator
的程度是未指定的,但至少
- 成员类型
Alloc::value_type
必须存在。 - 当作为未求值操作数处理时,表达式
std::declval<Alloc&>().allocate(std::size_t{})
必须是格式良好的。
示例
本节需要改进。您可以通过编辑此文档页面来帮助我们。