std::vector
的推导指南
来自 cppreference.cn
在头文件 <vector> 中定义 |
||
template< class InputIt, class Alloc = std::allocator< |
(1) | (C++17 起) |
template< ranges::input_range R, class Alloc = std::allocator<ranges::range_value_t<R>> > |
(2) | (C++23 起) |
1) 这个推导指南为 vector 提供,允许从迭代器范围进行推导。此重载仅在
InputIt
满足 LegacyInputIterator 且 Alloc
满足 Allocator 时参与重载决议。注意:库确定类型不满足 LegacyInputIterator 的程度未指定,但至少整数类型不符合输入迭代器的条件。同样,确定类型不满足 Allocator 的程度也未指定,但至少成员类型 Alloc::value_type
必须存在,并且表达式 std::declval<Alloc&>().allocate(std::size_t{}) 在被视为未求值操作数时必须是合法的。
[编辑] 注意
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_lib_containers_ranges |
202202L |
(C++23) | 范围感知构造与插入;重载 (2) |
[编辑] 示例
运行此代码
#include <vector> int main() { std::vector<int> v = {1, 2, 3, 4}; // uses explicit deduction guide to deduce std::vector<int> std::vector x(v.begin(), v.end()); // deduces std::vector<std::vector<int>::iterator> // first phase of overload resolution for list-initialization selects the candidate // synthesized from the initializer-list constructor; second phase is not performed // and deduction guide has no effect std::vector y{v.begin(), v.end()}; }