顾名思义,std::generate是一种STL算法,用于根据生成器函数生成数字,然后将这些值分配给容器中[第一个,最后一个]范围内的元素。
生成器函数必须由用户定义,并被连续调用以分配编号。
模板函数:
void generate (ForwardIterator first, ForwardIterator last, Generator gen); first: Forward iterator pointing to the first element of the container. last: Forward iterator pointing to the last element of the container. gen:A generator function, based upon which values will be assigned. 返回: none Since, it has a void return type, so it does not return any value.
// C++ program to demonstrate the use of std::generate
#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
std::generate(v1.begin(), v1.end(), 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
下一个: C++中的std::generate_n
相关用法
注:本文由纯净天空筛选整理自 std::generate in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。