generate
template<class _FwdIt,class _Fn> inline
void generate(_FwdIt _First, _FwdIt _Last, _Fn _Func)
将函数对象生成的元素赋值给容器。
参数
first 和 last 都为正向迭代器,[first, last) 用于赋值的范围;
func自定义规则,lambda函数或者函数,或者函数对象。
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <string>
#include<iterator>
int main()
{
//函数
std::vector<int> 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,
?generate_n
函数原型
template<class _OutIt, class _Diff, class _Fn> inline
_OutIt generate_n(_OutIt _Dest, const _Diff _Count_raw, _Fn _Func)
将函数对象生成的元素赋值给容器n个元素。
参数
_Dest 填充容器
_Diff _Count_raw 数目
_Func?自定义规则,lambda函数或者函数,或者函数对象
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <string>
#include<iterator>
int main()
{
//函数
std::vector<int> 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,
|