c++ 使用类生成随机数

 

// generate algorithm example
#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;
}

输出

myvector contains: 79 85 70 70 77 30 63 55
myvector contains: 1 2 3 4 5 6 7 8

 

posted @ 2019-05-20 01:31  anobscureretreat  阅读(561)  评论(0编辑  收藏  举报