std::ranges::iota, std::ranges::iota_result
来自cppreference.com
在标头 <numeric> 定义
|
||
调用签名 |
||
template< std::input_or_output_iterator O, std::sentinel_for<O> S, std::weakly_incrementable T > |
(1) | (C++23 起) |
template< std::weakly_incrementable T, ranges::output_range<const T&> R > constexpr iota_result<ranges::borrowed_iterator_t<R>, T> |
(2) | (C++23 起) |
辅助类型 |
||
template< class O, class T > using iota_result = ranges::out_value_result<O, T>; |
(3) | (C++23 起) |
用依次递增的值填充范围 [
first,
last)
,起始为 value 并重复应用 ++value。
等价操作:
*(first) = value; *(first + 1) = ++value; *(first + 2) = ++value; *(first + 3) = ++value; ...
目录 |
[编辑] 参数
first, last | - | 要以从 value 开始依次递增的数值填充的元素范围的迭代器-哨位对 |
value | - | 起始值;表达式 ++value 必须良构 |
[编辑] 返回值
{last, value + ranges::distance(first, last)}
[编辑] 复杂度
准确 last - first 次递增和赋值。
[编辑] 可能的实现
struct iota_fn { template<std::input_or_output_iterator O, std::sentinel_for<O> S, std::weakly_incrementable T> requires std::indirectly_writable<O, const T&> constexpr iota_result<O, T> operator()(O first, S last, T value) const { while (first != last) { *first = as_const(value); ++first; ++value; } return {std::move(first), std::move(value)}; } template<std::weakly_incrementable T, std::ranges::output_range<const T&> R> constexpr iota_result<std::ranges::borrowed_iterator_t<R>, T> operator()(R&& r, T value) const { return (*this)(std::ranges::begin(r), std::ranges::end(r), std::move(value)); } }; inline constexpr iota_fn iota; |
[编辑] 注解
该函数以 APL 编程语言中的整数函数 ⍳ 命名。
功能特性测试宏 | 值 | 标准 | 功能特性 |
---|---|---|---|
__cpp_lib_ranges_iota |
202202L |
(C++23) | std::ranges::iota
|
[编辑] 示例
使用 vector 的迭代器(std::vector<std::list<T>::iterator>)作为代理,对 std::list 中的元素进行洗牌,因为 ranges::shuffle 无法直接应用于 std::list。
运行此代码
#include <algorithm> #include <functional> #include <iostream> #include <list> #include <numeric> #include <random> #include <vector> template <typename Proj = std::identity> void println(auto comment, std::ranges::input_range auto&& range, Proj proj = {}) { for (std::cout << comment; auto const &element : range) std::cout << proj(element) << ' '; std::cout << '\n'; } int main() { std::list<int> list(8); // 以升序值填充 list: 0, 1, 2, ..., 7 std::ranges::iota(list, 0); println("list: ", list); // 迭代器的 vector(见示例的注释) std::vector<std::list<int>::iterator> vec(list.size()); // 以 list 各连续元素的迭代器填充 std::ranges::iota(vec.begin(), vec.end(), list.begin()); std::ranges::shuffle(vec, std::mt19937 {std::random_device {}()}); println("通过 vector 所见的 list: ", vec, [](auto it) { return *it; }); }
可能的输出:
list: 0 1 2 3 4 5 6 7 通过 vector 所见的 list: 5 7 6 0 1 3 4 2
[编辑] 参阅
以复制的方式赋给定值到范围中所有元素 (函数模板) | |
(C++20) |
赋给定值到范围中元素 (算法函数对象) |
赋连续函数调用结果到范围中所有元素 (函数模板) | |
(C++20) |
将函数结果保存到范围中 (算法函数对象) |
(C++20) |
由通过重复对某个初值自增所生成的序列组成的 view (类模板) (定制点对象) |
(C++11) |
从初始值开始连续递增填充范围 (函数模板) |