std::ranges::iota, std::ranges::iota_result
来自cppreference.com
| 在标头 <numeric> 定义
|
||
| 调用签名 |
||
| |
(1) | (C++23 起) |
| |
(2) | (C++23 起) |
| 辅助类型 |
||
| |
(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
|
示例
使用 std::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
