跳到主要内容

std::ranges::fill_n() 算法

// (1)
constexpr O fill_n( O first, std::iter_difference_t<O> n, const T& value );

参数类型是泛型的,并具有以下约束

  • T - (无)
  • O - std::output_iterator<const T&>

将给定值赋给范围 [first; first + n) 中的所有元素。

本页描述的函数类实体是niebloids

参数

first

要修改的元素范围的起始。

n

要修改的元素数量。

要赋的值。

返回值

一个与 first + n 比较相等的输出迭代器。

复杂度

精确地 n 次赋值。

异常

(无)

可能的实现

ranges::fill_n
struct fill_n_fn
{
template<class T, std::output_iterator<const T&> O>
constexpr O operator()(O first, std::iter_difference_t<O> n, const T& value) const
{
for (std::iter_difference_t<O> i {}; i != n; ++first, ++i)
*first = value;
return first;
}
};

inline constexpr fill_n_fn fill_n {};

示例

Main.cpp
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

void println(const auto& v)
{
for (const auto& elem : v)
std::cout << ' ' << elem;
std::cout << '\n';
}

int main()
{
constexpr auto n {010};

std::vector<std::string> v(n, "▓▓░░");
println(v);

std::ranges::fill_n(v.begin(), n, "░░▓▓");
println(v);
}
输出
 ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░
░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓
本文源自此 CppReference 页面。它可能为了改进或编辑者偏好而有所改动。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::ranges::fill_n() 算法

// (1)
constexpr O fill_n( O first, std::iter_difference_t<O> n, const T& value );

参数类型是泛型的,并具有以下约束

  • T - (无)
  • O - std::output_iterator<const T&>

将给定值赋给范围 [first; first + n) 中的所有元素。

本页描述的函数类实体是niebloids

参数

first

要修改的元素范围的起始。

n

要修改的元素数量。

要赋的值。

返回值

一个与 first + n 比较相等的输出迭代器。

复杂度

精确地 n 次赋值。

异常

(无)

可能的实现

ranges::fill_n
struct fill_n_fn
{
template<class T, std::output_iterator<const T&> O>
constexpr O operator()(O first, std::iter_difference_t<O> n, const T& value) const
{
for (std::iter_difference_t<O> i {}; i != n; ++first, ++i)
*first = value;
return first;
}
};

inline constexpr fill_n_fn fill_n {};

示例

Main.cpp
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

void println(const auto& v)
{
for (const auto& elem : v)
std::cout << ' ' << elem;
std::cout << '\n';
}

int main()
{
constexpr auto n {010};

std::vector<std::string> v(n, "▓▓░░");
println(v);

std::ranges::fill_n(v.begin(), n, "░░▓▓");
println(v);
}
输出
 ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░
░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓
本文源自此 CppReference 页面。它可能为了改进或编辑者偏好而有所改动。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。