std::generate是一种STL算法,用于根据生成器函数生成数字,然后将这些值分配给容器中[第一个,最后一个]范围内的元素。
生成器函数必须由用户定义,并被连续调用以分配编号。
现在,有一种情况,我们只想为前n个元素分配值,为此,我们有另一个STL算法std::generate_n,其语法如下:模板函数:
OutputIterator generate_n (OutputIterator first, Size n, Generator gen); first: Output iterator pointing to the beginning of the container. n:No. of elements to be assigned a value, using generator function. gen:A generator function for generating the values. 返回: It doesnot have a void return type like std::generate, but, in fact, it returns an iterator pointing to the element that follows the last element whose value has been generated.
// C++ program to demonstrate the use of std::generate_n
#include <iostream>
#include <vector>
#include <algorithm>
// Defining the generator function
int gen()
{
static int i = 0;
return ++i;
}
using namespace std;
int main()
{
int i;
// Declaring a vector of size 10
vector<int> v1(10);
// using std::generate_n
std::generate_n(v1.begin(), 10, gen);
vector<int>::iterator i1;
for (i1 = v1.begin(); i1 != v1.end(); ++i1) {
cout << *i1 << " ";
}
return 0;
}
输出:
1 2 3 4 5 6 7 8 9 10
相关用法
注:本文由纯净天空筛选整理自 std::generate_n in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。