zoukankan      html  css  js  c++  java
  • c++ 生成容器元素生成随机数

    // random_shuffle example
    #include <iostream>     // cout
    #include <algorithm>    // random_shuffle
    #include <vector>       // vector
    #include <ctime>        // time
    #include <cstdlib>      // rand, srand
    using namespace std;
    // random generator function:
    int myrandom (int i) { return rand()%i;}
    
    int main () {
      srand ( unsigned ( time(0) ) );
      vector<int> myvector;
    
      // set some values:
      for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9
    
      // using built-in random generator:
      random_shuffle ( myvector.begin(), myvector.end() );
    
     // print out content:
      cout << "using built-in random generator ,  myvector contains:";
      for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        cout << ' ' << *it;
      cout << '
    ';
    
      // using myrandom:
      random_shuffle ( myvector.begin(), myvector.end(), myrandom);
    
      // print out content:
      cout << " using myrandom  ,  myvector contains:";
      for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        cout << ' ' << *it;
    
      cout << '
    ';
    
      return 0;
    }

    输出

    using built-in random generator ,  myvector contains: 1 4 8 5 9 7 2 3 6
    using myrandom  ,  myvector contains: 3 7 8 9 4 2 5 1 6
  • 相关阅读:
    FTP Protocol
    File Operations
    Ubuntu Install Chinese Input Method
    Vim Intro
    ISA Introduction
    Fourier Transform
    Process/Thread Synchronization
    Process Synchronization-Example 2
    leetcode 栈和队列类型题
    leetcode 字符串类型题
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10891797.html
Copyright © 2011-2022 走看看