【C++库函数】C++生成高质量随机数的方法

1, 2 通用模板

image

#include <iostream>
#include <random>

int main() {
    // 第一步:初始化真随机种子(使用硬件熵源)
    std::random_device rd;  
    
    // 第二步:选择高性能引擎(推荐 mt19937)
    std::mt19937 gen(rd());  // 用 random_device 的输出来种子初始化引擎
    
    // 第三步:定义分布(例如生成 [1, 100] 的均匀整数)
    std::uniform_int_distribution<> dis(1, 100);
    
    // 生成随机数
    for (int i = 0; i < 5; ++i) {
        std::cout << dis(gen) << " ";  // 每次调用 dis(gen) 生成一个随机数
    }
    
    return 0;
}

3 示例

image

#include <vector>
#include <random>

std::vector<uint8_t> generate_crypto_random(size_t len) {
    std::random_device rd;  // 需要确认实现是否基于硬件熵源(如Linux的/dev/urandom)
    std::vector<uint8_t> buffer(len);
    for (auto& byte : buffer) {
        byte = static_cast<uint8_t>(rd());  // 直接使用 random_device
    }
    return buffer;
}

4 优化 + 对比

image

std::random_device rd;
std::seed_seq seed_seq{rd(), rd(), rd()};  // 混合多个熵源
std::mt19937 gen(seed_seq);

image

5 验证方法

image

#include <map>
#include <iostream>

void test_distribution() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 6);
    
    std::map<int, int> counts;
    for (int i = 0; i < 10000; ++i) {
        ++counts[dis(gen)];
    }
    
    for (const auto& pair : counts) {
        std::cout << "Value " << pair.first << ": " << pair.second << " times\n";
    }
}

image

posted @ 2025-03-04 22:04  Tshaxz  阅读(107)  评论(0)    收藏  举报
Language: HTML