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()
翻译自: https://www.includehelp.com/stl/std-fill_n-function-with-example.aspx
c++stl和std