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.
Returns:
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
#include
#include
// 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 v1(10);
// using std::generate_n
std::generate_n(v1.begin(), 10, gen);
vector::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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。