fill_n

将新值分配给以特定元素开始的范围中的指定数量的元素。

template<class OutputIterator, class Size, class Type> 
   OutputIterator fill_n( 
      OutputIterator First,  
      Size Count,  
      const Type& Val 
   ); 

参数

  • First
    在赋值为 Val 的范围中寻址第一个元素的位置的输出迭代器。

  • Count
    指定元素个数的带符号或不带符号的整数类型将被赋予值。

  • Val
    将要分配给 [First](First + Count) 范围中的元素的值。

返回值

如果 Count > 零,元素迭代器会遵循最后填充的元素,否则遵循第一个元素。

备注

目标范围必须是有效的;所有指针必须是不可引用的,并且通过增量可从第一个到达最后一个。 复杂性与范围大小是线性关系。

fill_n 有两个相关的窗体:

有关这些功能如何运行的信息,请参阅 经过检查的迭代器

示例

// alg_fill_n.cpp
// compile using /EHsc
#include <vector>
#include <algorithm>
#include <iostream>

int main() 
{
    using namespace std;
    vector <int> v;

    for ( auto i = 0 ; i < 9 ; ++i )
        v.push_back( 0 );

    cout << "  vector v = ( " ;
    for ( const auto &w : v )
        cout << w << " ";
    cout << ")" << endl;

    // Fill the first 3 positions with a value of 1, saving position.
    auto pos = fill_n( v.begin(), 3, 1 );

    cout << "modified v = ( " ;
    for ( const auto &w : v )
        cout << w << " ";
    cout << ")" << endl;

    // Fill the next 3 positions with a value of 2, using last position.
    fill_n( pos, 3, 2 );

    cout << "modified v = ( " ;
    for ( const auto &w : v )
        cout << w << " ";
    cout << ")" << endl;

    // Fill the last 3 positions with a value of 3, using relative math.
    fill_n( v.end()-3, 3, 3 );

    cout << "modified v = ( " ;
    for ( const auto &w : v )
        cout << w << " ";
    cout << ")" << endl;
}

Output

  vector v = ( 0 0 0 0 0 0 0 0 0 )
modified v = ( 1 1 1 0 0 0 0 0 0 )
modified v = ( 1 1 1 2 2 2 0 0 0 )
modified v = ( 1 1 1 2 2 2 3 3 3 )

要求

标头: <算法>

命名空间: std

请参见

参考

标准模板库