1. 程式人生 > >c++ 容器元素填充(generate)

c++ 容器元素填充(generate)

 

#include <iostream>     // cout
#include <algorithm>    // generate
#include <vector>       // vector
#include <ctime>        // time
#include <cstdlib>      // rand, srand
using namespace std;
// function generator:
int RandomNumber () { return (rand()%100); }

// class generator:
struct c_unique { int current; c_unique() {current=0;} int operator()() {return ++current;} } UniqueNumber; int main () { srand ( unsigned ( time(0) ) ); vector<int> myvector (8); generate (myvector.begin(), myvector.end(), RandomNumber);// 通過函式生成 cout << "myvector contains:
"; for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) cout << ' ' << *it; cout << '\n'; generate (myvector.begin(), myvector.end(), UniqueNumber);// 通過結構體生成 cout << "myvector contains:"; for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) cout
<< ' ' << *it; cout << '\n'; return 0; }