std::ranges::iota() 算法
- 自 C++20 起
- 简化
- 详细
// (1)
constexpr iota_result<O, T> iota( O first, S last, T value );
// (2)
constexpr iota_result<ranges::borrowed_iterator_t<R>, T> iota( R&& r, T value );
参数类型是泛型的,并具有以下约束
I
-std::input_or_output_iterator
S
-std::sentinel_for<O>
R
-ranges::output_range<const T&>
T
-std::weakly_incrementable
此外,每个重载都有以下约束
- (1) -
std::indirectly_writable<O, const T&>
// (1)
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> iota( O first, S last, T value );
// (2)
template<std::weakly_incrementable T, ranges::output_range<const T&> R>
constexpr iota_result<ranges::borrowed_iterator_t<R>, T> iota( R&& r, T value );
辅助类型定义如下:
template< class O, class T >
using iota_result = ranges::out_value_result<O, T>;
用顺序递增的值填充范围 [first
; last
),从 value 开始并重复评估 ++value
。
等效操作
*(first) = value;
*(first + 1) = ++value;
*(first + 2) = ++value;
*(first + 3) = ++value;
...
本页描述的函数类实体是niebloids。
参数
first second | 要从 |
值 | 要存储的初始值。 |
返回值
{
last,
value + ranges::distance(first, last)
}
复杂度
精确地 last - first
次递增和赋值。
异常
(无)
可能的实现
iota(1) 和 iota(2)
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 中的整数函数 ⍳
命名。它是 C++98 中未包含但于 C++11 中进入标准库的 STL 组件之一。
示例
Main.cpp
#include <algorithm>
#include <functional>
#include <iostream>
#include <list>
#include <numeric>
#include <random>
#include <vector>
template <typename Proj = std::identity>
inline void print(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);
// Fill the list with ascending values: 0, 1, 2, ..., 7
std::ranges::iota(list, 0);
print("Contents of the list: ", list);
// A vector of iterators (see the comment to Example)
std::vector<std::list<int>::iterator> vec(list.size());
// Fill with iterators to consecutive list's elements
std::ranges::iota(vec.begin(), vec.end(), list.begin());
std::ranges::shuffle(vec, std::mt19937 {std::random_device {}()});
print("Contents of the list viewed via vector: ", vec, [](auto it) { return *it; });
}
输出
Contents of the list: 0 1 2 3 4 5 6 7
Contents of the list viewed via vector: 5 7 6 0 1 3 4 2