generate(beg,end,op)和generate_n(beg,num,op)的特点
1:迭代器类型:generate—前向迭代器,generate_n----输出迭代器
2:返回值:void
3:算法功能:调用op()产生新值,并赋给区间[beg,end)或beg开头的目标区间
4:复杂度:线性复杂度
5:对于generate_n调用者必须保证目标区间空间不小于num,否则应采用插入迭代器
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
vector<int>c1 = { 1,2,3,4,5 };
cout << "c1:";
copy(c1.begin(), c1.end(), ostream_iterator<int>(cout, " "));
cout << endl;
generate(c1.begin(), c1.end(), []()->int { return rand() % 10; });
cout << "c1:";
copy(c1.begin(), c1.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
vector<int>c1 = {1,2,3,4};
cout << "c1:";
copy(c1.begin(), c1.end(), ostream_iterator<int>(cout, " "));
cout << endl;
generate_n(c1.begin(),4, []()->int { return rand() % 16; });
cout << "c1:";
copy(c1.begin(), c1.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
一点小改动:假如我们c1中有4个元素,但是我们要插入6个元素,这时我们应使用插入迭代器,但是这样会在原有元素的末尾插入6个元素,和我们想象的优点不一样,所以我们应该在generate_n()前调用c1.clear()
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
vector<int>c1 = {1,2,3,4};
cout << "c1:";
copy(c1.begin(), c1.end(), ostream_iterator<int>(cout, " "));
cout << endl;
generate_n(back_inserter(c1),6, []()->int { return rand() % 16; });
cout << "c1:";
// 1 2 3 4 9 3 14 4 1 12
copy(c1.begin(), c1.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
vector<int>c1 = {1,2,3,4};
cout << "c1:";
copy(c1.begin(), c1.end(), ostream_iterator<int>(cout, " "));
cout << endl;
c1.clear();
generate_n(back_inserter(c1),6, []()->int { return rand() % 16; });
cout << "c1:";
// 9 3 14 4 1 12
copy(c1.begin(), c1.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}