STL 之generate和generate_n
作用:用来生成元素,并将其填充到一个序列中。
定义:
- #include <algorithm>
- template <class forwardItr, class function>
- void generate(forwardItr first, forwardItr last, function gen);
- template <class forwardItr, class size, class function>
- void generate_n(forwardItr first, size n, function gen);
示例代码:
- #include <iostream>
- #include <list>
- #include <string>
- #include <numeric>
- #include <iterator>
- #include <vector>
- #include <functional>
- #include <algorithm>
- using namespace std;
- int nextNum() {
- static int n = 1;
- return n++;
- }
- int main() {
- // 定义容器和 输出流迭代器
- vector<int> vecList(8);
- ostream_iterator<int> screen(cout, " ");
- // nextNum 是函数指针,其必须是有返回值无参函数
- generate(vecList.begin(),vecList.end(),nextNum);
- cout << "vecList :" << endl;
- copy(vecList.begin(),vecList.end(),screen);
- cout << endl;
- generate_n(vecList.begin(),3,nextNum);
- cout << "vecList :" << endl;
- copy(vecList.begin(),vecList.end(),screen);
- cout << endl;
- return 0;
- }
运行结果:vecList :
1 2 3 4 5 6 7 8
vecList :
9 10 11 4 5 6 7 8