std::ranges::fill_n
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
呼叫簽名 (Call signature) |
||
template< class T, std::output_iterator<const T&> O > constexpr O fill_n( O first, std::iter_difference_t<O> n, const T& value ); |
(C++20 起) (直到 C++26) |
|
template< class O, class T = std::iter_value_t<O> > requires std::output_iterator<O, const T&> |
(C++26 起) | |
將給定的 value 賦值給範圍 [
first,
first + n)
中的所有元素。
本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
first | - | 要修改的元素範圍的起始迭代器 |
n | - | 要修改的元素數量 |
value | - | 要賦值的值 |
[編輯] 返回值
一個輸出迭代器,與 first + n 比較相等。
[編輯] 複雜度
恰好 n 次賦值。
[編輯] 可能的實現
struct fill_n_fn { template<class O, class T = std::iter_value_t<O>> requires std::output_iterator<O, const T&> 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 {}; |
[編輯] 注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_algorithm_default_value_type |
202403 |
(C++26) | 演算法的列表初始化 |
[編輯] 示例
執行此程式碼
#include <algorithm> #include <complex> #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{8}; std::vector<std::string> v(n, "▓▓░░"); println(v); std::ranges::fill_n(v.begin(), n, "░░▓▓"); println(v); std::vector<std::complex<double>> nums{{1, 3}, {2, 2}, {4, 8}}; println(nums); #ifdef __cpp_lib_algorithm_default_value_type std::ranges::fill_n(nums.begin(), 2, {4, 2}); #else std::ranges::fill_n(nums.begin(), 2, std::complex<double>{4, 2}); #endif println(nums); }
輸出
▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ▓▓░░ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ ░░▓▓ (1,3) (2,2) (4,8) (4,2) (4,2) (4,8)
[編輯] 參閱
(C++20) |
給一個範圍的元素賦某個值 (演算法函式物件) |
(C++20) |
將一定數量的元素複製到一個新位置 (演算法函式物件) |
(C++20) |
將一個函式的結果儲存在一個範圍中 (演算法函式物件) |
(C++20) |
對一個範圍的元素應用函式 (演算法函式物件) |
(C++26) |
用來自均勻隨機位生成器的隨機數填充範圍 (演算法函式物件) |
將給定值複製賦給一個範圍中的 N 個元素 (函式模板) |