std::fill_n

 

翻译:https://en.cppreference.com/w/cpp/algorithm/fill_n

 

定义在头文件<algorithm>

函数声明:

template< class OutputIt, class Size, class T >
void fill_n( OutputIt first, Size count, const T& value ); // (until C++11)
template< class OutputIt, class Size, class T >
OutputIt fill_n( OutputIt first, Size count, const T& value ); //(since C++11) (until C++20)
template< class OutputIt, class Size, class T >
constexpr OutputIt fill_n( OutputIt first, Size count, const T& value ); // (since C++20)
template< class ExecutionPolicy, class ForwardIt, class Size, class T >
ForwardIt fill_n( ExecutionPolicy&& policy, ForwardIt first, Size count, const T& value );
(2)	//(since C++17)

 

函数解释:

1)如果参数 count > 0, 那么在参数 first 的开始位置,分配 count 个 value 元素。否则什么也不做

2)同1,按照策略执行。但是重载方案不会参与,除非 

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

或者

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

是真。

 

函数参数:

first:要被修改元素的起始翻译的开始地址

count:修改元素的数量

value:被分配的元素的值

policy:使用的执行策略。

 

类型要求:

OutputIt 和 ForwardIt 必须要满足对应的要求

 

返回值:

 

函数实现:

template<class OutputIt, class Size, class T>
OutputIt fill_n(OutputIt first, Size count, const T& value)
{
    for (Size i = 0; i < count; i++) {
        *first++ = value;
    }
    return first;
}

 

 

例子:

#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
 
int main()
{
    std::vector<int> v1{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
 
    std::fill_n(v1.begin(), 5, -1);
 
    std::copy(begin(v1), end(v1), std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
}

 

输出结果:

-1 -1 -1 -1 -1 5 6 7 8 9

 

posted @ 2022-06-06 14:46  王清河  阅读(295)  评论(0编辑  收藏  举报