主要函数 //generate template<class FwdIt, class Gen> void generate(FwdIt first, FwdIt alst, Gen g); 即:*(first+N) = g(); N(-[0, last-first) //generate_n template<class OutIt, class Pred, class Gen> void generate_n(OutIt first, Dist n, Gen g); 即:*(first+N) = g() N(-[0,n) example #include <iostream> #include <vector> #include <algorithm> #include <cstdlib> #include <iterator> using namespace std; class Fibonacci { int f1; int f2; public: Fibonacci(int start1, int start2) { f1 = start1; f2 = start2; } int operator()() { int r = f1 + f2; f1 = f2; f2 = r; return r; } }; int main(int argc, char *argv[]) { vector<int> v1(10); generate(v1.begin(), v1.end(), Fibonacci(0, 1)); copy(v1.begin(), v1.end(), ostream_iterator<int>(cout, " ")); cout << endl; vector<int> v2(10); generate(v2.begin(), v2.end(), Fibonacci(0, 1)); copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " ")); cout << endl; system("pause"); return 0; } generate generate_n rand #include <iostream> #include <vector> #include <ctime> #include <algorithm> #include <cstdlib> #include <iterator> using namespace std; template<class T> class MyRandom { }; template<> class MyRandom<int> { public: MyRandom() { srand(time(NULL)); } int operator()() { int result = rand() % 100; return result; } }; template<> class MyRandom<double> { public: MyRandom() { srand(time(NULL)); } double operator()() { double result = rand()%100*0.01f; return result; } }; int main(int argc, char argv[]) { cout << "产生[0, 100)间10个整型随机数:" << endl; vector<int> v1(10); generate(v1.begin(), v1.end(), MyRandom<int>()); copy(v1.begin(), v1.end(), ostream_iterator<int>(cout, " ")); cout << endl; cout << "产生[0, 1)间10个浮点随机数:" << endl; vector<double> v2(10); generate(v2.begin(), v2.end(), MyRandom<double>()); copy(v2.begin(), v2.end(), ostream_iterator<double>(cout, " ")); cout << endl; system("pause"); return 0; }