algorithm::fill_n()
描述 (Description)
C ++函数std::algorithm::fill_n()将值赋给第一个指向的序列的前n个元素。
声明 (Declaration)
以下是std :: algorithm :: fill_n()函数形式std :: algorithm头的声明。
C++98
template <class OutputIterator, class Size, class T>
OutputIterator fill_n (OutputIterator first, Size n, const T& val);
参数 (Parameters)
first - 将迭代器输出到初始位置。
n - 要填充的元素数。
val - 用于填充范围的值。
返回值
返回一个迭代器,指向最后一个元素填充后面的元素。
异常 (Exceptions)
如果元素赋值或迭代器上的操作抛出异常,则抛出异常。
请注意,无效参数会导致未定义的行为。
时间复杂
线性。
例子 (Example)
以下示例显示了std :: algorithm :: fill_n()函数的用法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void) {
vector<int> v(5, 1);
fill_n(v.begin() + 2, 3, 4);
cout << "Vector contains following elements" << endl;
for (auto it = v.begin(); it != v.end(); ++it)
cout << *it << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 -
Vector contains following elements
1
1
4
4
4