c++stl和std_std :: fill_n()函数以及C ++ STL中的示例

c++stl和std

C ++ STL std :: fill_n()函数 (C++ STL std::fill_n() function)

fill_n() function is a library function of algorithm header, it is used to assign a value to the n elements of a container, it accepts an iterator pointing to the starting position in the container, n (number of elements) and a value to be assigned to the n elements, and assigns the value.

fill_n()函数算法标头的库函数,用于将值分配给容器的n个元素,它接受指向容器中起始位置的迭代器n (元素数)和一个值被分配给n个元素,并分配值。

Note: To use fill_n() function – include <algorithm> header or you can simple use <bits/stdc++.h> header file.

注意:要使用fill_n()函数 –包括<algorithm>头文件,或者您可以简单地使用<bits / stdc ++。h>头文件。

Syntax of std::fill_n() function

std :: fill_n()函数的语法

    std::fill_n(iterator start, n, value);

Parameter(s):

参数:

  • iterator start – an iterator pointing to the position from where we have to assign the value to the next n elements.

    迭代器开始 –迭代器指向必须将值分配给接下来的n个元素的位置。

  • n – number of elements to be assigned with the given value.

    n –要分配给定值的元素数。

  • value – a value of the same type to be assigned to the n elements.

    value –要分配给n个元素的相同类型的值。

Return value: void – it returns noting.

返回值: void –返回注释。

Example:

例:

    Input:
    vector<int> v(10);
    
    //filling 10 elements with -1
    fill(v.begin(), 10, -1);
    
    Output:
    -1 -1 -1 -1 -1 -1 -1 -1 -1 -1

C ++ STL程序演示std :: fill_n()函数的使用 (C++ STL program to demonstrate use of std::fill_n() function)

In this program, we are going to fill the n elements of a vector.

在此程序中,我们将填充向量的n个元素。

//C++ STL program to demonstrate use of
//std::fill_n() function
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    //vector
    vector<int> v(10);

    //filling all elements with -1
    fill_n(v.begin(), 10, -1);

    //printing vector elements
    cout << "v: ";
    for (int x : v)
        cout << x << " ";
    cout << endl;

    //filling initial 3 elements with 100
    fill_n(v.begin(), 3, 100);

    //printing vector elements
    cout << "v: ";
    for (int x : v)
        cout << x << " ";
    cout << endl;

    //filling rest of the elements with 200
    fill_n(v.begin() + 3, 7, 200);

    //printing vector elements
    cout << "v: ";
    for (int x : v)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

输出量

v: -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
v: 100 100 100 -1 -1 -1 -1 -1 -1 -1
v: 100 100 100 200 200 200 200 200 200 200

Reference: C++ std::fill_n()

参考: C ++ std :: fill_n()

翻译自: https://www.includehelp.com/stl/std-fill_n-function-with-example.aspx

c++stl和std

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值