名稱空間
變體
操作

std::stack 的推導指南

來自 cppreference.com
< cpp‎ | 容器‎ |
定義於標頭檔案 <stack>
template< class Container >

stack( Container )

    -> stack<typename Container::value_type, Container>;
(1) (C++17 起)
template< class Container, class Alloc >

stack( Container, Alloc )

    -> stack<typename Container::value_type, Container>;
(2) (C++17 起)
template< class InputIt >

stack( InputIt, InputIt )

    -> stack<typename std::iterator_traits<InputIt>::value_type>;
(3) (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>>;
(4) (C++23 起)
template< ranges::input_range R >

stack( std::from_range_t, R&& )

    -> stack<ranges::range_value_t<R>>;
(5) (C++23 起)
template< ranges::input_range R, class Allocator >

stack( std::from_range_t, R&&, Allocator )
    -> stack<ranges::range_value_t<R>,

       std::deque<ranges::range_value_t<R>, Allocator>>;
(6) (C++23 起)

stack 提供了這些推導指南,以允許從底層容器型別進行推導。

1) 從引數推導底層容器型別。
2)(1) 相同,但提供了分配器。
3) 使用 std::deque<typename std::iterator_traits<InputIt>::value_type> 作為底層容器型別,從迭代器推導元素型別。
4)(3) 相同,但提供了分配器。
5)std::from_range_t 標籤和 input_range 推導元素型別。
6)(5) 相同,但提供了分配器。

這些過載只有在以下情況下才參與過載決議:

注意:庫確定型別不滿足 LegacyInputIterator 的程度未指定,但至少整數型別不符合輸入迭代器的條件。同樣,它確定型別不滿足 Allocator 的程度未指定,但至少成員型別 Alloc::value_type 必須存在,並且表示式 std::declval<Alloc&>().allocate(std::size_t{}) 在被視為未求值運算元時必須格式良好。

[編輯] 注意

特性測試 標準 特性
__cpp_lib_adaptor_iterator_pair_constructor 202106L (C++23) std::queuestd::stack 的迭代器對建構函式;過載 (2)(4)
__cpp_lib_containers_ranges 202202L (C++23) 範圍感知構造和插入;過載 (5)(6)

[編輯] 示例

#include <stack>
#include <vector>
 
int main()
{
    std::vector<int> v = {1, 2, 3, 4};
    std::stack s{v}; // guide #1 deduces std::stack<int, vector<int>>
}