C++11 隨機數 random


#include <iostream>
#include <random>

int main() { 
    std::random_device rd;
    std::default_random_engine engine(rd());
    std::uniform_int_distribution<> dis(0, 2);
    auto dice = std::bind(dis, engine);
    int res = dice();
    /*
     0、北京
     1、合肥
     2、成都
     */
    cout << res << " " << res % 3 << endl;
    cout << "0、北京 "<< endl;
    cout << "1、合肥 "<< endl;
    cout << "2、成都 "<< endl;
    
    return 0;
}

engine

engine 是一個帶狀態的隨機數生成器,在預定義的范圍 [min, max] 以內生成隨機數

engine 本身重載了 () 運算符,使用起來類似函數

distribution

如果我們想要自定義生成隨機數的范圍,或者會生成的隨機數分布有要求,則需要使用 distribution

 

 

資料:

https://blog.csdn.net/qq_34784753/article/details/79600809

https://www.jianshu.com/p/730b32475115

https://zhuanlan.zhihu.com/p/112577796

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM