templateinline void generate(_FwdIt _First, _FwdIt _Last, _Fn _Func)
将函数对象生成的元素赋值给容器。
参数
first 和 last 都为正向迭代器,[first, last) 用于赋值的范围;
func自定义规则,lambda函数或者函数,或者函数对象。
#includegenerate_n#include #include #include #include #include int main() { //函数 std::vector b(5);//没确定配容器大小,不分配内存 std::generate(std::begin(b), std::end(b), value); std::cout << "b fill vector: "; std::for_each(std::begin(b), std::end(b), [](int value) { std::cout << value << ", "; }); std::cout << std::endl; //仿函数 std::generate(std::begin(b), std::end(b), fill()); std::cout << "b fill vector: "; std::for_each(std::begin(b), std::end(b), [](int value) { std::cout << value << ", "; }); std::cout << std::endl; //lambda std::generate(std::begin(b), std::end(b), [&]() { static int a = 10; return a++; }); std::cout << "b fill vector: "; std::for_each(std::begin(b), std::end(b), [](int value) { std::cout << value << ", "; }); std::cout << std::endl; return -1; } //输出 b fill vector: 0, 1, 2, 3, 4, b fill vector: 6, 7, 8, 9, 10, b fill vector: 10, 11, 12, 13, 14,
函数原型
templateinline _OutIt generate_n(_OutIt _Dest, const _Diff _Count_raw, _Fn _Func)
将函数对象生成的元素赋值给容器n个元素。
参数
_Dest 填充容器
_Diff _Count_raw 数目
_Func 自定义规则,lambda函数或者函数,或者函数对象
#include#include #include #include #include #include int main() { //函数 std::vector b(5);//没确定配容器大小,不分配内存 std::generate_n(std::begin(b), b.size(), value); std::cout << "b fill vector: "; std::for_each(std::begin(b), std::end(b), [](int value) { std::cout << value << ", "; }); std::cout << std::endl; //仿函数 std::generate_n(std::begin(b), b.size(), fill()); std::cout << "b fill vector: "; std::for_each(std::begin(b), std::end(b), [](int value) { std::cout << value << ", "; }); std::cout << std::endl; //lambda std::generate_n(std::begin(b), b.size(), [&]() { static int a = 10; return a++; }); std::cout << "b fill vector: "; std::for_each(std::begin(b), std::end(b), [](int value) { std::cout << value << ", "; }); std::cout << std::endl; return -1; } //输出 b fill vector: 0, 1, 2, 3, 4, b fill vector: 6, 7, 8, 9, 10, b fill vector: 10, 11, 12, 13, 14,



