std::ranges::fill() 算法
- 自 C++20 起
- 简化
- 详细
// (1)
template<
class T,
std::output_iterator<const T&> O,
std::sentinel_for<O> S
>
constexpr O fill( O first, S last, const T& value );
// (2)
template<
class T,
ranges::output_range<const T&> R
>
constexpr ranges::borrowed_iterator_t<R> fill( R&& r, const T& value );
参数类型是泛型的,并具有以下约束
T
- (无)O
-std::output_iterator<const T&>
S
-std::sentinel_for<O>
- (2) -
R
-std::ranges::output_range<const T&>
// (1)
template<
class T,
std::output_iterator<const T&> O,
std::sentinel_for<O> S
>
constexpr O fill( O first, S last, const T& value );
// (2)
template<
class T,
ranges::output_range<const T&> R
>
constexpr ranges::borrowed_iterator_t<R> fill( R&& r, const T& value );
- (1) 将给定值赋给范围 [
first
;last
) 中的元素。 - (2) 与 (1) 相同,但使用
r
作为源范围,如同使用ranges::begin(r)
作为first
和ranges::end(r)
作为last
。
本页描述的函数类实体是niebloids。
参数
first last | 要检查的元素范围。 |
r | 要检查的元素范围。 |
值 | 要赋的值。 |
返回值
与 last
相等的输出迭代器。
复杂度
恰好 last - first
次赋值。
异常
(无)
可能的实现
ranges::fill
struct fill_fn
{
template<class T, std::output_iterator<const T&> O, std::sentinel_for<O> S>
constexpr O operator()(O first, S last, const T& value) const
{
while (first != last)
*first++ = value;
return first;
}
template<class T, ranges::output_range<const T&> R>
constexpr ranges::borrowed_iterator_t<R> operator()(R&& r, const T& value) const
{
return (*this)(ranges::begin(r), ranges::end(r), value);
}
};
inline constexpr fill_fn fill;
示例
以下代码使用 ranges::fill
将 std::vector<int>
的所有元素首先设置为 -1
,然后设置为 10
。
Main.cpp
#include <algorithm>
#include <iostream>
#include <vector>
void println(std::vector<int> const& vi)
{
for (int e : vi)
std::cout << e << ' ';
std::cout << '\n';
}
int main()
{
std::vector<int> v {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::ranges::fill(v.begin(), v.end(), -1);
println(v);
std::ranges::fill(v, 10);
println(v);
}
输出
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
10 10 10 10 10 10 10 10 10 10