C++随机数生成实战:从rand()到C++11 random库的全面升级指南
如果你还在用 rand() % 100 来生成随机数,那么这篇文章就是为你准备的。我见过太多项目,包括一些已经上线的商业系统,还在依赖着C语言时代遗留下来的随机数生成方式。这些代码不仅存在统计偏差,在需要高质量随机数的场景下——比如游戏道具掉落、密码生成、蒙特卡洛模拟——往往会带来难以察觉的bug。更糟糕的是,当这些系统需要移植到不同平台时,随机数行为的不一致性会让调试变成一场噩梦。
C++11引入的 <random> 库彻底改变了这一局面。它不仅仅是一个“更好的随机数生成器”,而是一套完整的、工业级的随机数生成框架。从简单的骰子模拟到复杂的概率分布采样,现代C++提供了远比 rand() 更强大、更安全、更可预测的工具集。本文将带你深入理解传统方法的局限,并手把手教你如何将代码升级到现代C++标准,让你的随机数生成既专业又可靠。
1. 传统方法的陷阱:为什么rand()不再够用
1.1 rand()的工作原理与固有缺陷
rand() 函数是C标准库的一部分,它基于线性同余生成器(LCG)算法。简单来说,它通过一个数学公式生成伪随机序列:
next = (a * current + c) % m
其中 current 是当前状态,a、c、m 是预定义的常数。这个算法的问题在于它的周期性和统计特性。
周期性问题:大多数实现中,rand() 的周期是 2³²,大约43亿个数字。对于需要大量随机数的应用(如长时间运行的模拟),这个周期可能不够用,导致序列重复。
模偏差问题:这是 rand() 最严重的问题之一。当你使用 rand() % N 来获取特定范围的随机数时,如果 RAND_MAX + 1 不能被 N 整除,某些数字出现的概率会更高。
让我用一个具体的例子说明这个问题:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
void demonstrate_mod_bias() {
srand(time(nullptr));
const int N = 7; // 假设我们需要0-6的随机数
const int RAND_MAX_PLUS_1 = RAND_MAX + 1;
const int full_cycles = RAND_MAX_PLUS_1 / N;
const int remainder = RAND_MAX_PLUS_1 % N;
std::cout << "RAND_MAX = " << RAND_MAX << std::endl;
std::cout << "N = " << N << std::endl;
std::cout << "完整周期数: " << full_cycles << std::endl;
std::cout << "余数: " << remainder << std::endl;
// 前remainder个数字会多出现一次
std::cout << "数字 0 到 " << (remainder - 1)
<< " 出现的概率稍高" << std::endl;
}
注意:模偏差在实际应用中可能很微妙。如果你需要生成1-100的随机数,而RAND_MAX是32767,那么1-67的数字出现的概率会比68-100的数字高约0.5%。在需要公平性的场景(如赌博游戏、抽奖系统)中,这种偏差是不可接受的。
1.2 srand()的局限性与线程安全问题
srand() 用于设置随机数种子,但它在多线程环境下的行为是未定义的。考虑以下场景:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <thread>
#include <vector>
void thread_function(int id) {
// 错误做法:每个线程都调用srand
srand(time(nullptr) + id);
for (int i = 0; i < 3; ++i) {
std::cout << "线程" << id << ": " << rand() % 100 << std::endl;
}
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 3; ++i) {
threads.emplace_back(thread_function, i);
}
for (auto& t : threads) {
t.join();
}
return 0;
}
这段代码有多个问题:
- 多个线程可能同时修改全局的随机数状态
time(nullptr)的精度是秒级,多个线程可能在同秒内启动- 即使使用更精确的时间,竞争条件仍然存在
rand()在不同平台上的实现差异:
| 平台/编译器 | RAND_MAX值 | 算法 | 周期 |
|---|---|---|---|
| GCC (glibc) | 2147483647 | LCG | 2³¹ |
| MSVC | 32767 | LCG | 2³¹ |
| 某些嵌入式系统 | 32767 | 简单LCG | 可能更短 |
这种不一致性意味着同一段使用 rand() 的代码在不同平台上可能产生不同的随机数序列,这对于需要可重现结果的科学计算或跨平台游戏来说是灾难性的。
1.3 实际案例:骰子模拟中的偏差
让我们通过一个简单的骰子模拟来观察传统方法的问题:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <map>
#include <iomanip>
void simulate_dice_rolls_old(int num_rolls) {
srand(time(nullptr));
std::map<int, int> counts;
for (int i = 0; i < num_rolls; ++i) {
int roll = (rand() % 6) + 1; // 1-6
counts[roll]++;
}
std::cout << "使用rand() % 6的结果:" << std::endl;
for (int i = 1; i <= 6; ++i) {
double percentage = (counts[i] * 100.0) / num_rolls;
std::cout << i << ": " << counts[i] << "次 ("
<< std::fixed << std::setprecision(2)
<< percentage << "%)" << std::endl;
}
}
运行10万次后,你可能会发现某些数字的出现频率比其他数字高0.1%-0.3%。虽然这个差异看起来很小,但在需要严格公平性的场景中(如在线赌博或科学实验),这是不可接受的。
2. C++11 random库的核心组件
2.1 随机数引擎:不只是mt19937
C++11的 <random> 库将随机数生成分为三个部分:引擎、分布和种子。让我们先深入了解各种引擎的特性。
常用随机数引擎对比:
| 引擎类型 | 周期长度 | 速度 | 内存占用 | 适用场景 |
|---|---|---|---|---|
std::minstd_rand | 2³¹-1 | 快 | 小 | 简单应用,兼容性要求 |
std::mt19937 | 2¹⁹⁹³⁷-1 | 中等 | 2.5KB | 通用场景,质量好 |
std::mt19937_64 | 2¹⁹⁹³⁷-1 | 中等 | 5KB | 需要64位随机数 |
std::ranlux24 | 10¹⁷¹ | 慢 | 小 | 高质量,统计测试 |
std::ranlux48 | 10⁸⁵⁹¹ | 慢 | 小 | 极高品质要求 |
mt19937(梅森旋转算法)是目前最常用的引擎,它有这些关键特性:
- 周期长达2¹⁹⁹³⁷-1,对于绝大多数应用都足够
- 623维均匀分布,通过了多种统计测试
- 相对高效,适合大多数应用场景
#include <random>
#include <iostream>
#include <vector>
void explore_mt19937() {
// 创建引擎实例
std::mt19937 engine;
// 默认构造的引擎使用固定种子
std::cout << "默认种子生成的第一个数: " << engine() << std::endl;
// 使用随机设备作为种子
std::random_device rd;
std::mt19937 seeded_engine(rd());
std::cout << "随机种子生成的第一个数: " << seeded_engine() << std::endl;
// 保存和恢复引擎状态
std::stringstream state_stream;
state_stream << seeded_engine; // 保存状态
// 生成一些数字
std::vector<unsigned int> numbers;
for (int i = 0; i < 5; ++i) {
numbers.push_back(seeded_engine());
}
// 恢复状态
state_stream >> seeded_engine;
// 重新生成,应该得到相同的序列
std::cout << "\n恢复状态后生成的数字: ";
for (int i = 0; i < 5; ++i) {
std::cout << seeded_engine() << " ";
// 验证与之前保存的相同
if (seeded_engine() != numbers[i]) {
std::cout << "\n错误:序列不匹配!" << std::endl;
}
}
std::cout << std::endl;
}
提示:
std::random_device在大多数现代系统上会使用硬件随机数生成器(如RDRAND指令),但在某些实现中可能回退到伪随机。如果需要真正的加密安全随机数,应该使用专门的加密库。
2.2 随机数分布:从均匀到复杂
分布器是将引擎产生的原始随机数转换为特定概率分布的数字。这是C++11 random库最强大的特性之一。
均匀分布是最基础也是最重要的分布:
#include <random>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
void uniform_distribution_examples() {
std::random_device rd;
std::mt19937 engine(rd());
// 整数均匀分布 [1, 6] - 骰子
std::uniform_int_distribution<int> dice(1, 6);
// 浮点数均匀分布 [0.0, 1.0)
std::uniform_real_distribution<double> real_uni(0.0, 1.0);
// 生成并统计
const int num_samples = 100000;
std::vector<int> counts(6, 0);
for (int i = 0; i < num_samples; ++i) {
int roll = dice(engine);
counts[roll - 1]++;
}
std::cout << "骰子模拟结果(" << num_samples << "次投掷):" << std::endl;
for (int i = 0; i < 6; ++i) {
double percentage = (counts[i] * 100.0) / num_samples;
std::cout << i + 1 << ": " << counts[i] << " ("
<< std::fixed << std::setprecision(3)
<< percentage << "%)" << std::endl;
}
// 验证均匀性
double expected = 100.0 / 6.0; // 约16.667%
std::cout << "\n理论期望值: " << expected << "%" << std::endl;
std::cout << "最大偏差: "
<< std::setprecision(3)
<< *std::max_element(counts.begin(), counts.end()) * 100.0 / num_samples - expected
<< "%" << std::endl;
}
其他常用分布:
void other_distributions_demo() {
std::random_device rd;
std::mt19937 engine(rd());
// 正态分布(高斯分布)
std::normal_distribution<double> normal(0.0, 1.0); // 均值0,标准差1
// 泊松分布(描述稀有事件)
std::poisson_distribution<int> poisson(4.0); // λ=4
// 指数分布(描述时间间隔)
std::exponential_distribution<double> exponential(1.0); // λ=1
std::cout << "正态分布样本: ";
for (int i = 0; i < 5; ++i) {
std::cout << normal(engine) << " ";
}
std::cout << "\n泊松分布样本: ";
for (int i = 0; i < 5; ++i) {
std::cout << poisson(engine) << " ";
}
std::cout << "\n指数分布样本: ";
for (int i = 0; i < 5; ++i) {
std::cout << exponential(engine) << " ";
}
std::cout << std::endl;
}
2.3 种子管理与可重现性
在科学计算和调试中,能够重现相同的随机数序列至关重要。C++11的random库为此提供了完善的工具。
#include <random>
#include <iostream>
#include <sstream>
#include <vector>
class ReproducibleRandom {
private:
std::mt19937 engine;
std::string last_seed_str;
public:
// 使用指定种子初始化
explicit ReproducibleRandom(unsigned int seed = std::random_device{}())
: engine(seed) {
std::stringstream ss;
ss << seed;
last_seed_str = ss.str();
}
// 生成[min, max]范围内的随机整数
int uniform_int(int min, int max) {
std::uniform_int_distribution<int> dist(min, max);
return dist(engine);
}
// 生成[min, max)范围内的随机浮点数
double uniform_real(double min, double max) {
std::uniform_real_distribution<double> dist(min, max);
return dist(engine);
}
// 保存当前状态
std::string save_state() const {
std::stringstream ss;
ss << engine;
return ss.str();
}
// 恢复状态
void restore_state(const std::string& state) {
std::stringstream ss(state);
ss >> engine;
}
// 获取当前种子(用于重现)
std::string get_seed_info() const {
return last_seed_str;
}
// 重置为新的随机种子
void reseed(unsigned int new_seed) {
engine.seed(new_seed);
std::stringstream ss;
ss << new_seed;
last_seed_str = ss.str();
}
};
void demonstrate_reproducibility() {
std::cout << "=== 可重现性演示 ===" << std::endl;
// 使用固定种子
ReproducibleRandom rng1(12345);
std::cout << "RNG1种子: " << rng1.get_seed_info() << std::endl;
// 生成一些数字
std::vector<int> sequence1;
for (int i = 0; i < 5; ++i) {
int num = rng1.uniform_int(1, 100);
sequence1.push_back(num);
std::cout << num << " ";
}
std::cout << std::endl;
// 创建另一个使用相同种子的RNG
ReproducibleRandom rng2(12345);
std::cout << "\nRNG2(相同种子)生成的序列: ";
for (int i = 0; i < 5; ++i) {
int num = rng2.uniform_int(1, 100);
std::cout << num << " ";
if (num != sequence1[i]) {
std::cout << "\n错误:序列不匹配!" << std::endl;
}
}
std::cout << "\n(验证通过:两个序列完全相同)" << std::endl;
// 演示状态保存和恢复
std::cout << "\n=== 状态保存/恢复演示 ===" << std::endl;
ReproducibleRandom rng3(42);
// 生成两个数字
std::cout << "前两个数字: " << rng3.uniform_int(1, 100) << ", "
<< rng3.uniform_int(1, 100) << std::endl;
// 保存状态
std::string state = rng3.save_state();
// 再生成两个数字
std::cout << "接下来两个数字: " << rng3.uniform_int(1, 100) << ", "
<< rng3.uniform_int(1, 100) << std::endl;
// 恢复状态
rng3.restore_state(state);
// 应该生成与之前相同的"接下来两个数字"
std::cout << "恢复状态后: " << rng3.uniform_int(1, 100) << ", "
<< rng3.uniform_int(1, 100) << std::endl;
}
3. 实战应用:五个真实场景的现代实现
3.1 场景一:公平的骰子模拟器
在游戏开发中,公平的随机数生成至关重要。让我们实现一个专业的骰子模拟器:
#include <random>
#include <iostream>
#include <vector>
#include <map>
#include <chrono>
#include <iomanip>
class DiceSimulator {
private:
std::mt19937 engine;
std::uniform_int_distribution<int> dist;
public:
DiceSimulator(int sides = 6)
: dist(1, sides) {
// 使用高精度时间戳和随机设备的混合种子
auto time_seed = std::chrono::high_resolution_clock::now()
.time_since_epoch().count();
std::random_device rd;
std::seed_seq seed_seq{rd(), static_cast<unsigned int>(time_seed)};
engine.seed(seed_seq);
}
// 单次投掷
int roll() {
return dist(engine);
}
// 多次投掷并统计
std::map<int, int> roll_multiple(int times) {
std::map<int, int> results;
for (int i = 0; i < times; ++i) {
results[roll()]++;
}
return results;
}
// 测试公平性
void test_fairness(int total_rolls = 1000000) {
auto results = roll_multiple(total_rolls);
double expected = total_rolls / static_cast<double>(dist.max() - dist.min() + 1);
std::cout << "\n公平性测试 (" << total_rolls << "次投掷):" << std::endl;
std::cout << std::setw(8) << "面值"
<< std::setw(12) << "出现次数"
<< std::setw(12) << "百分比"
<< std::setw(12) << "偏差" << std::endl;
double max_deviation = 0.0;
for (const auto& [value, count] : results) {
double percentage = (count * 100.0) / total_rolls;
double expected_percent = 100.0 / (dist.max() - dist.min() + 1);
double deviation = std::abs(percentage - expected_percent);
max_deviation = std::max(max_deviation, deviation);
std::cout << std::setw(8) << value
<< std::setw(12) << count
<< std::setw(11) << std::fixed << std::setprecision(4)
<< percentage << "%"
<< std::setw(11) << deviation << "%" << std::endl;
}
std::cout << "\n最大偏差: " << std::fixed << std::setprecision(4)
<< max_deviation << "%" << std::endl;
std::cout << "理论期望: " << 100.0 / (dist.max() - dist.min() + 1)
<< "% 每面" << std::endl;
}
};
void dice_simulation_demo() {
std::cout << "=== 专业骰子模拟器 ===" << std::endl;
// 创建不同面数的骰子
DiceSimulator d6(6); // 标准六面骰
DiceSimulator d20(20); // D20骰子,用于桌面角色扮演游戏
std::cout << "\n六面骰测试:" << std::endl;
d6.test_fairness(1000000);
std::cout << "\nD20骰测试:" << std::endl;
d20.test_fairness(1000000);
// 模拟实际游戏场景
std::cout << "\n=== 游戏场景模拟 ===" << std::endl;
std::cout << "攻击检定(D20):" << std::endl;
for (int i = 0; i < 10; ++i) {
int roll = d20.roll();
std::cout << "第" << i+1 << "次: " << roll;
if (roll == 20) std::cout << " (暴击!)";
else if (roll == 1) std::cout << " (大失败!)";
std::cout << std::endl;
}
}
3.2 场景二:密码生成器
生成安全的随机密码需要高质量的随机数。让我们实现一个密码生成器:
#include <random>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
class PasswordGenerator {
private:
std::mt19937 engine;
// 字符集定义
const std::string lowercase = "abcdefghijklmnopqrstuvwxyz";
const std::string uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const std::string digits = "0123456789";
const std::string special = "!@#$%^&*()-_=+[]{}|;:,.<>?";
// 从字符串中随机选择字符
char random_char_from(const std::string& charset) {
std::uniform_int_distribution<size_t> dist(0, charset.size() - 1);
return charset[dist(engine)];
}
public:
PasswordGenerator() {
std::random_device rd;
std::seed_seq seed_seq{rd(), rd(), rd()}; // 多个随机源混合
engine.seed(seed_seq);
}
// 生成指定长度的密码
std::string generate(int length, bool use_lower = true,
bool use_upper = true, bool use_digits = true,
bool use_special = false) {
if (length < 4) {
throw std::invalid_argument("密码长度至少为4个字符");
}
// 构建可用字符集
std::string all_chars;
std::vector<std::string> required_sets;
if (use_lower) {
all_chars += lowercase;
required_sets.push_back(lowercase);
}
if (use_upper) {
all_chars += uppercase;
required_sets.push_back(uppercase);
}
if (use_digits) {
all_chars += digits;
required_sets.push_back(digits);
}
if (use_special) {
all_chars += special;
required_sets.push_back(special);
}
if (all_chars.empty()) {
throw std::invalid_argument("至少选择一种字符类型");
}
std::string password;
password.reserve(length);
// 确保每种类型至少有一个字符
for (const auto& charset : required_sets) {
password += random_char_from(charset);
}
// 填充剩余长度
std::uniform_int_distribution<size_t> dist(0, all_chars.size() - 1);
while (password.length() < static_cast<size_t>(length)) {
password += all_chars[dist(engine)];
}
// 随机打乱(避免前几个字符总是来自必需集合)
std::shuffle(password.begin(), password.end(), engine);
return password;
}
// 评估密码强度
static int evaluate_strength(const std::string& password) {
int score = 0;
// 长度评分
if (password.length() >= 8) score += 1;
if (password.length() >= 12) score += 1;
if (password.length() >= 16) score += 1;
// 字符种类评分
bool has_lower = false, has_upper = false;
bool has_digit = false, has_special = false;
for (char c : password) {
if (islower(c)) has_lower = true;
else if (isupper(c)) has_upper = true;
else if (isdigit(c)) has_digit = true;
else has_special = true;
}
int char_types = has_lower + has_upper + has_digit + has_special;
score += (char_types - 1); // 至少2种得1分,3种得2分,4种得3分
return std::min(score, 5); // 最高5分
}
};
void password_generator_demo() {
std::cout << "=== 安全密码生成器 ===" << std::endl;
PasswordGenerator generator;
// 生成不同类型的密码
std::cout << "\n1. 简单密码(仅字母数字):" << std::endl;
for (int i = 0; i < 3; ++i) {
std::string pwd = generator.generate(10, true, true, true, false);
int strength = PasswordGenerator::evaluate_strength(pwd);
std::cout << " " << pwd << " [强度: " << strength << "/5]" << std::endl;
}
std::cout << "\n2. 强密码(包含特殊字符):" << std::endl;
for (int i = 0; i < 3; ++i) {
std::string pwd = generator.generate(16, true, true, true, true);
int strength = PasswordGenerator::evaluate_strength(pwd);
std::cout << " " << pwd << " [强度: " << strength << "/5]" << std::endl;
}
std::cout << "\n3. 批量生成(用于测试):" << std::endl;
std::vector<std::string> passwords;
for (int i = 0; i < 1000; ++i) {
passwords.push_back(generator.generate(12, true, true, true, true));
}
// 检查重复(在高质量随机数中应该很少)
std::sort(passwords.begin(), passwords.end());
auto last = std::unique(passwords.begin(), passwords.end());
int duplicates = passwords.end() - last;
std::cout << " 生成1000个密码,重复数: " << duplicates
<< " (" << (duplicates * 100.0 / 1000) << "%)" << std::endl;
// 统计字符分布
std::map<char, int> char_counts;
for (const auto& pwd : passwords) {
for (char c : pwd) {
char_counts[c]++;
}
}
std::cout << "\n4. 字符分布统计(前10个):" << std::endl;
std::vector<std::pair<char, int>> sorted_chars(char_counts.begin(),
char_counts.end());
std::sort(sorted_chars.begin(), sorted_chars.end(),
[](const auto& a, const auto& b) { return a.second > b.second; });
for (int i = 0; i < std::min(10, (int)sorted_chars.size()); ++i) {
double percentage = (sorted_chars[i].second * 100.0) /
(passwords.size() * 12);
std::cout << " '" << sorted_chars[i].first << "': "
<< sorted_chars[i].second << "次 ("
<< std::fixed << std::setprecision(2) << percentage << "%)"
<< std::endl;
}
}
3.3 场景三:蒙特卡洛模拟
蒙特卡洛方法依赖高质量的随机数进行概率模拟。让我们用C++11 random库实现π的估算:
#include <random>
#include <iostream>
#include <chrono>
#include <cmath>
#include <iomanip>
#include <vector>
#include <thread>
#include <future>
class MonteCarloPi {
private:
std::mt19937_64 engine; // 使用64位引擎以获得更好的精度
std::uniform_real_distribution<double> dist;
public:
MonteCarloPi() : dist(0.0, 1.0) {
// 使用高熵种子
std::random_device rd;
std::seed_seq seed_seq{rd(), rd(), rd(), rd()};
engine.seed(seed_seq);
}
// 单线程版本
double estimate_pi_single_thread(long long num_points) {
long long inside_circle = 0;
for (long long i = 0; i < num_points; ++i) {
double x = dist(engine);
double y = dist(engine);
if (x * x + y * y <= 1.0) {
inside_circle++;
}
}
return 4.0 * inside_circle / num_points;
}
// 多线程版本
double estimate_pi_multi_thread(long long total_points, int num_threads = 4) {
if (num_threads <= 0) {
num_threads = std::thread::hardware_concurrency();
if (num_threads == 0) num_threads = 4;
}
long long points_per_thread = total_points / num_threads;
std::vector<std::future<long long>> futures;
// 启动多个线程
for (int i = 0; i < num_threads; ++i) {
futures.push_back(std::async(std::launch::async,
[this, points_per_thread, i]() {
return this->count_points_in_circle(points_per_thread, i);
}));
}
// 汇总结果
long long total_inside = 0;
for (auto& future : futures) {
total_inside += future.get();
}
return 4.0 * total_inside / total_points;
}
private:
long long count_points_in_circle(long long num_points, int thread_id) {
// 每个线程使用不同的种子
std::seed_seq seed_seq{std::random_device{}(),
static_cast<unsigned int>(thread_id),
static_cast<unsigned int>(std::chrono::system_clock::now()
.time_since_epoch().count())};
std::mt19937_64 local_engine;
local_engine.seed(seed_seq);
std::uniform_real_distribution<double> local_dist(0.0, 1.0);
long long inside_circle = 0;
for (long long i = 0; i < num_points; ++i) {
double x = local_dist(local_engine);
double y = local_dist(local_engine);
if (x * x + y * y <= 1.0) {
inside_circle++;
}
}
return inside_circle;
}
};
void monte_carlo_demo() {
std::cout << "=== 蒙特卡洛π估算 ===" << std::endl;
MonteCarloPi simulator;
const long long test_points[] = {1000, 10000, 100000, 1000000, 10000000};
std::cout << std::setw(12) << "点数"
<< std::setw(15) << "估算值"
<< std::setw(15) << "误差(%)"
<< std::setw(15) << "时间(ms)"
<< std::setw(15) << "线程数" << std::endl;
for (long long points : test_points) {
auto start = std::chrono::high_resolution_clock::now();
// 单线程
double pi_estimate = simulator.estimate_pi_single_thread(points);
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
double error = std::abs(pi_estimate - M_PI) / M_PI * 100;
std::cout << std::setw(12) << points
<< std::setw(15) << std::setprecision(10) << pi_estimate
<< std::setw(14) << std::setprecision(4) << error << "%"
<< std::setw(15) << duration.count()
<< std::setw(15) << "1" << std::endl;
// 多线程(使用所有可用核心)
start = std::chrono::high_resolution_clock::now();
int num_threads = std::thread::hardware_concurrency();
if (num_threads == 0) num_threads = 4;
pi_estimate = simulator.estimate_pi_multi_thread(points, num_threads);
end = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
error = std::abs(pi_estimate - M_PI) / M_PI * 100;
std::cout << std::setw(12) << points
<< std::setw(15) << std::setprecision(10) << pi_estimate
<< std::setw(14) << std::setprecision(4) << error << "%"
<< std::setw(15) << duration.count()
<< std::setw(15) << num_threads << std::endl;
std::cout << std::string(70, '-') << std::endl;
}
// 演示不同随机数质量的影响
std::cout << "\n=== 随机数质量对结果的影响 ===" << std::endl;
const int num_trials = 100;
const long long points_per_trial = 100000;
std::vector<double> estimates_mt19937;
std::vector<double> estimates_rand;
// 使用mt19937
{
std::random_device rd;
std::mt19937_64 engine(rd());
std::uniform_real_distribution<double> dist(0.0, 1.0);
for (int trial = 0; trial < num_trials; ++trial) {
long long inside = 0;
for (long long i = 0; i < points_per_trial; ++i) {
double x = dist(engine);
double y = dist(engine);
if (x * x + y * y <= 1.0) inside++;
}
estimates_mt19937.push_back(4.0 * inside / points_per_trial);
}
}
// 使用rand()(传统方法)
{
srand(static_cast<unsigned>(time(nullptr)));
for (int trial = 0; trial < num_trials; ++trial) {
long long inside = 0;
for (long long i = 0; i < points_per_trial; ++i) {
double x = rand() / double(RAND_MAX);
double y = rand() / double(RAND_MAX);
if (x * x + y * y <= 1.0) inside++;
}
estimates_rand.push_back(4.0 * inside / points_per_trial);
}
}
// 计算统计信息
auto calculate_stats = [](const std::vector<double>& values) {
double sum = 0.0;
double min_val = std::numeric_limits<double>::max();
double max_val = std::numeric_limits<double>::lowest();
for (double val : values) {
sum += val;
min_val = std::min(min_val, val);
max_val = std::max(max_val, val);
}
double mean = sum / values.size();
double variance = 0.0;
for (double val : values) {
variance += (val - mean) * (val - mean);
}
variance /= values.size();
return std::make_tuple(mean, std::sqrt(variance), min_val, max_val);
};
auto [mean_mt, std_mt, min_mt, max_mt] = calculate_stats(estimates_mt19937);
auto [mean_rand, std_rand, min_rand, max_rand] = calculate_stats(estimates_rand);
std::cout << "\n" << std::setw(20) << "统计量"
<< std::setw(20) << "mt19937"
<< std::setw(20) << "rand()" << std::endl;
std::cout << std::setw(20) << "平均值"
<< std::setw(20) << std::setprecision(8) << mean_mt
<< std::setw(20) << std::setprecision(8) << mean_rand << std::endl;
std::cout << std::setw(20) << "标准差"
<< std::setw(20) << std::setprecision(8) << std_mt
<< std::setw(20) << std::setprecision(8) << std_rand << std::endl;
std::cout << std::setw(20) << "最小值"
<< std::setw(20) << std::setprecision(8) << min_mt
<< std::setw(20) << std::setprecision(8) << min_rand << std::endl;
std::cout << std::setw(20) << "最大值"
<< std::setw(20) << std::setprecision(8) << max_mt
<< std::setw(20) << std::setprecision(8) << max_rand << std::endl;
std::cout << std::setw(20) << "理论π值"
<< std::setw(20) << std::setprecision(8) << M_PI
<< std::setw(20) << std::setprecision(8) << M_PI << std::endl;
}
3.4 场景四:游戏中的随机事件系统
在游戏开发中,随机事件系统需要处理各种概率分布。让我们实现一个完整的游戏随机事件系统:
#include <random>
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <memory>
#include <algorithm>
class GameRandomSystem {
private:
std::mt19937 engine;
// 概率分布定义
struct LootItem {
std::string name;
double probability; // 0.0 - 1.0
int min_quantity;
int max_quantity;
};
struct EnemySpawn {
std::string type;
double weight; // 相对权重
int min_level;
int max_level;
};
public:
GameRandomSystem() {
std::random_device rd;
engine.seed(rd());
}
// 根据权重随机选择
template<typename T>
const T& weighted_choice(const std::vector<T>& items,
double (T::*weight_func)() const) {
if (items.empty()) {
throw std::runtime_error("物品列表为空");
}
// 计算总权重
double total_weight = 0.0;
for (const auto& item : items) {
total_weight += (item.*weight_func)();
}
// 生成随机数
std::uniform_real_distribution<double> dist(0.0, total_weight);
double random_value = dist(engine);
// 根据权重选择
double cumulative = 0.0;
for (const auto& item : items) {
cumulative += (item.*weight_func)();
if (random_value <= cumulative) {
return item;
}
}
// 理论上不会执行到这里
return items.back();
}
// 掉落物品生成
std::vector<std::pair<std::string, int>> generate_loot(
const std::vector<LootItem>& loot_table,
int luck_bonus = 0) {
std::vector<std::pair<std::string, int>> result;
for (const auto& item : loot_table) {
// 计算实际概率(受幸运值影响)
double actual_prob = std::min(1.0,
item.probability * (1.0 + luck_bonus * 0.01));
std::bernoulli_distribution drop_dist(actual_prob);
if (drop_dist(engine)) {
// 生成数量
std::uniform_int_distribution<int> qty_dist(
item.min_quantity, item.max_quantity);
int quantity = qty_dist(engine);
result.emplace_back(item.name, quantity);
}
}
return result;
}
// 敌人生成
std::vector<EnemySpawn> generate_enemies(
const std::vector<EnemySpawn>& spawn_table,
int area_level,
int num_enemies) {
std::vector<EnemySpawn> result;
result.reserve(num_enemies);
// 过滤适合当前等级的敌人
std::vector<EnemySpawn> available_enemies;
for (const auto& enemy : spawn_table) {
if (area_level >= enemy.min_level &&
area_level <= enemy.max_level) {
available_enemies.push_back(enemy);
}
}
if (available_enemies.empty()) {
return result;
}
// 根据权重选择敌人
for (int i = 0; i < num_enemies; ++i) {
// 使用lambda获取权重
auto weight_func = [](const EnemySpawn& e) { return e.weight; };
// 选择敌人类型
const EnemySpawn& chosen = weighted_choice_by_func(
available_enemies, weight_func);
result.push_back(chosen);
}
return result;
}
// 暴击判定
bool check_critical_hit(double base_crit_chance,
int dex_bonus = 0,
int luck_bonus = 0) {
// 计算实际暴击率
double actual_crit = base_crit_chance +
dex_bonus * 0.01 +
luck_bonus * 0.005;
actual_crit = std::clamp(actual_crit, 0.0, 0.95); // 上限95%
std::bernoulli_distribution crit_dist(actual_crit);
return crit_dist(engine);
}
// 伤害浮动计算
int calculate_damage(int base_damage,
double variance = 0.2, // ±20%
int strength_bonus = 0) {
// 基础伤害加上力量加成
int adjusted_damage = base_damage + strength_bonus;
// 应用随机浮动
std::uniform_real_distribution<double> dist(
1.0 - variance, 1.0 + variance);
double multiplier = dist(engine);
int final_damage = static_cast<int>(adjusted_damage * multiplier);
return std::max(1, final_damage); // 至少造成1点伤害
}
// 稀有物品的伪随机分布(防止连续不出的情况)
class PseudoRandomDistribution {
private:
double probability;
double counter;
std::mt19937& engine;
public:
PseudoRandomDistribution(double p, std::mt19937& eng)
: probability(p), counter(0.0), engine(eng) {}
bool check() {
counter += probability;
if (counter >= 1.0 ||
std::uniform_real_distribution<double>(0.0, 1.0)(engine) < counter) {
counter = 0.0;
return true;
}
return false;
}
void reset() { counter = 0.0; }
};
private:
template<typename T, typename Func>
const T& weighted_choice_by_func(const std::vector<T>& items, Func weight_func) {
if (items.empty()) {
throw std::runtime_error("物品列表为空");
}
double total_weight = 0.0;
for (const auto& item : items) {
total_weight += weight_func(item);
}
std::uniform_real_distribution<double> dist(0.0, total_weight);
double random_value = dist(engine);
double cumulative = 0.0;
for (const auto& item : items) {
cumulative += weight_func(item);
if (random_value <= cumulative) {
return item;
}
}
return items.back();
}
};
void game_random_system_demo() {
std::cout << "=== 游戏随机事件系统 ===" << std::endl;
GameRandomSystem game_rng;
// 定义掉落表
std::vector<GameRandomSystem::LootItem> loot_table = {
{"金币", 0.8, 1, 100},
{"治疗药水", 0.3, 1, 3},
{"魔法药水", 0.2, 1, 2},
{"普通装备", 0.15, 1, 1},
{"稀有装备", 0.05, 1, 1},
{"传奇装备", 0.01, 1, 1}
};
// 定义敌人生成表
std::vector<GameRandomSystem::EnemySpawn> enemy_table = {
{"哥布林", 50.0, 1, 10},
{"兽人", 30.0, 5, 20},
{"骷髅", 25.0, 10, 30},
{"巨龙", 1.0, 30, 50},
{"史莱姆", 40.0, 1, 5}
};
// 模拟战斗
std::cout << "\n1. 模拟战斗掉落:" << std::endl;
for (int battle = 1; battle <= 5; ++battle) {
std::cout << "\n战斗 #" << battle << ":" << std::endl;
auto loot = game_rng.generate_loot(loot_table, 10); // 10点幸运加成
if (loot.empty()) {
std::cout << " 没有掉落物品" << std::endl;
} else {
for (const auto& [item, quantity] : loot) {
std::cout << " " << item << " ×" << quantity << std::endl;
}
}
}
// 模拟敌人生成
std::cout << "\n2. 区域敌人生成(等级15):" << std::endl;
auto enemies = game_rng.generate_enemies(enemy_table, 15, 8);
std::map<std::string, int> enemy_counts;
for (const auto& enemy : enemies) {
enemy_counts[enemy.type]++;
}
for (const auto& [type, count] : enemy_counts) {
std::cout << " " << type << ": " << count << "只" << std::endl;
}
// 模拟暴击和伤害
std::cout << "\n3. 攻击模拟(基础暴击率15%,敏捷+20,幸运+10):" << std::endl;
const int num_attacks = 20;
int crit_count = 0;
for (int i = 0; i < num_attacks; ++i) {
bool is_crit = game_rng.check_critical_hit(0.15, 20, 10);
int damage = game_rng.calculate_damage(100, 0.2, 30); // 基础伤害100,浮动20%,力量+30
std::cout << " 攻击#" << (i+1) << ": " << damage << "伤害";
if (is_crit) {
std::cout << " [暴击!]";
crit_count++;
}
std::cout << std::endl;
}
double crit_rate = crit_count * 100.0 / num_attacks;
std::cout << "\n 实际暴击率: " << crit_rate << "%" << std::endl;
// 伪随机分布测试(用于稀有物品)
std::cout << "\n4. 伪随机分布测试(1%掉落率):" << std::endl;
GameRandomSystem::PseudoRandomDistribution prd(0.01,
*reinterpret_cast<std::mt19937*>(&game_rng)); // 注意:这里只是演示
const int num_trials = 1000;
int success_count = 0;
std::vector<int> intervals;
int current_interval = 0;
for (int i = 0; i < num_trials; ++i) {
current_interval++;
if (std::bernoulli_distribution(0.01)(*reinterpret_cast<std::mt19937*>(&game_rng))) {
success_count++;
intervals.push_back(current_interval);
current_interval = 0;
}
}
std::cout << " 标准随机:成功" << success_count << "次 ("
<< (success_count * 100.0 / num_trials) << "%)" << std::endl;
if (!intervals.empty()) {
double avg_interval = 0.0;
for (int interval : intervals) {
avg_interval += interval;
}
avg_interval /= intervals.size();
std::cout << " 平均间隔: " << avg_interval << "次尝试" << std::endl;
std::cout << " 最大间隔: " << *std::max_element(intervals.begin(), intervals.end())
<< "次尝试" << std::endl;
std::cout << " 最小间隔: " << *std::min_element(intervals.begin(), intervals.end())
<< "次尝试" << std::endl;
}
}
3.5 场景五:测试数据生成器
在软件测试中,需要生成各种边界情况和随机数据。让我们实现一个全面的测试数据生成器:
#include <random>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <ctime>
class TestDataGenerator {
private:
std::mt19937_64 engine;
// 字符集
const std::string lowercase_letters = "abcdefghijklmnopqrstuvwxyz";
const std::string uppercase_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const std::string digits = "0123456789";
const std::string symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?";
const std::string whitespace = " \t\n\r";
public:
TestDataGenerator(unsigned int seed = std::random_device{}())
: engine(seed) {}
// 设置种子(用于重现测试)
void set_seed(unsigned int seed) {
engine.seed(seed);
}
// 生成随机整数
int random_int(int min_val, int max_val) {
std::uniform_int_distribution<int> dist(min_val, max_val);
return dist(engine);
}
// 生成随机浮点数
double random_double(double min_val, double max_val) {
std::uniform_real_distribution<double> dist(min_val, max_val);
return dist(engine);
}
// 生成随机布尔值
bool random_bool(double true_probability = 0.5) {
std::bernoulli_distribution dist(true_probability);
return dist(engine);
}
// 生成随机字符串
std::string random_string(size_t length,
bool use_lower = true,
bool use_upper = true,
bool use_digits = true,
bool use_symbols = false,
bool use_whitespace = false) {
std::string charset;
if (use_lower) charset += lowercase_letters;
if (use_upper) charset += uppercase_letters;
if (use_digits) charset += digits;
if (use_symbols) charset += symbols;
if (use_whitespace) charset += whitespace;
if (charset.empty()) {
charset = lowercase_letters + uppercase_letters + digits;
}
std::uniform_int_distribution<size_t> dist(0, charset.size() - 1);
std::string result;
result.reserve(length);
for (size_t i = 0; i < length; ++i) {
result.push_back(charset[dist(engine)]);
}
return result;
}
// 生成随机日期时间
std::string random_datetime(int start_year = 2000, int end_year = 2024) {
std::uniform_int_distribution<int> year_dist(start_year, end_year);
std::uniform_int_distribution<int> month_dist(1, 12);
std::uniform_int_distribution<int> hour_dist(0, 23);
std::uniform_int_distribution<int> minute_dist(0, 59);
std::uniform_int_distribution<int> second_dist(0, 59);
int year = year_dist(engine);
int month = month_dist(engine);
// 处理不同月份的天数
int days_in_month;
if (month == 2) {
// 简单闰年判断
bool is_leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
days_in_month = is_leap ? 29 : 28;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
days_in_month = 30;
} else {
days_in_month = 31;
}
std::uniform_int_distribution<int> day_dist(1, days_in_month);
int day = day_dist(engine);
std::stringstream ss;
ss << std::setfill('0')
<< std::setw(4) << year << "-"
<< std::setw(2) << month << "-"
<< std::setw(2) << day << " "
<< std::setw(2) << hour_dist(engine) << ":"
<< std::setw(2) << minute_dist(engine) << ":"
<< std::setw(2) << second_dist(engine);
return ss.str();
}
// 生成边界测试数据
template<typename T>
std::vector<T> generate_boundary_cases() {
std::vector<T> cases;
if constexpr (std::is_integral_v<T>) {
// 整数边界值
cases.push_back(std::numeric_limits<T>::min());
cases.push_back(std::numeric_limits<T>::min() + 1);
cases.push_back(-1);
cases.push_back(0);
cases.push_back(1);
cases.push_back(std::numeric_limits<T>::max() - 1);
cases.push_back(std::numeric_limits<T>::max());
// 添加一些随机值
for (int i = 0; i < 10; ++i) {
cases.push_back(random_int(-1000, 1000));
}
}
else if constexpr (std::is_floating_point_v<T>) {
// 浮点数边界值
cases.push_back(-std::numeric_limits<T>::infinity());
cases.push_back(std::numeric_limits<T>::lowest());
cases.push_back(-std::numeric_limits<T>::max());
cases.push_back(-1.0);
cases.push_back(-0.0);
cases.push_back(0.0);
cases.push_back(std::numeric_limits<T>::min());
cases.push_back(1.0);
cases.push_back(std::numeric_limits<T>::max());
cases.push_back(std::numeric_limits<T>::infinity());
cases.push_back(std::numeric_limits<T>::quiet_NaN());
// 添加一些随机值
for (int i = 0; i < 10; ++i) {
cases.push_back(random_double(-1000.0, 1000.0));
}
}
return cases;
}
// 生成CSV测试数据
void generate_csv_test_data(const std::string& filename,
int num_rows,
const std::vector<std::string>& column_specs) {
std::ofstream file(filename);
if (!file.is_open()) {
throw std::runtime_error("无法打开文件: " + filename);
}
// 写入列头
for (size_t i = 0; i < column_specs.size(); ++i) {
file << "col_" << i;
if (i != column_specs.size() - 1) {
file << ",";
}
}
file << "\n";
// 生成数据行
for (int row = 0; row < num_rows; ++row) {
for (size_t col = 0; col < column_specs.size(); ++col) {
const std::string& spec = column_specs[col];
if (spec == "int") {
file << random_int(-10000, 10000);
}
else if (spec == "float") {
file << std::fixed << std::setprecision(6)
<< random_double(-1000.0, 1000.0);
}
else if (spec == "bool") {
file << (random_bool() ? "true" : "false");
}
else if (spec == "string") {
std::string str = random_string(random_int(5, 50));
// CSV转义
if (str.find(',') != std::string::npos ||
str.find('"') != std::string::npos ||
str.find('\n') != std::string::npos) {
// 替换双引号为两个双引号
size_t pos = 0;
while ((pos = str.find('"', pos)) != std::string::npos) {
str.replace(pos, 1, "\"\"");
pos += 2;
}
file << "\"" << str << "\"";
} else {
file << str;
}
}
else if (spec == "datetime") {
file << random_datetime();
}
else if (spec == "email") {
file << random_string(8) << "@"
<< random_string(6) << "."
<< (random_bool(0.7) ? "com" : "org");
}
else if (spec == "phone") {
file << "+1-"
<< std::setfill('0') << std::setw(3) << random_int(200, 999) << "-"
<< std::setw(3) << random_int(0, 999) << "-"
<< std::setw(4) << random_int(0, 9999);
}
else {
// 默认生成字符串
file << random_string(10);
}
if (col != column_specs.size() - 1) {
file << ",";
}
}
file << "\n";
// 显示进度
if ((row + 1) % 1000 == 0) {
std::cout << "已生成 " << (row + 1) << " 行数据..." << std::endl;
}
}
file.close();
std::cout << "测试数据已保存到: " << filename
<< " (" << num_rows << " 行)" << std::endl;
}
// 性能测试:生成大量数据并测量时间
void performance_test(int total_items = 1000000) {
std::cout << "\n=== 性能测试 (生成 " << total_items << " 个随机数) ===" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
// 测试整数生成
std::vector<int> ints;
ints.reserve(total_items);
for (int i = 0; i < total_items; ++i) {
ints.push_back(random_int(-1000000, 1000000));
}
auto mid = std::chrono::high_resolution_clock::now();
auto int_time = std::chrono::duration_cast<std::chrono::milliseconds>(mid - start);
// 测试浮点数生成
std::vector<double> doubles;
doubles.reserve(total_items);
for (int i = 0; i < total_items; ++i) {
doubles.push_back(random_double(-1000000.0, 1000000.0));
}
auto end = std::chrono::high_resolution_clock::now();
auto double_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - mid);
auto total_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "整数生成: " << int_time.count() << "ms ("
<< (total_items * 1000.0 / int_time.count()) << " 个/秒)" << std::endl;
std::cout << "浮点数生成: " << double_time.count() << "ms ("
<< (total_items * 1000.0 / double_time.count()) << " 个/秒)" << std::endl;
std::cout << "总计: " << total_time.count() << "ms ("
<< (2 * total_items * 1000.0 / total_time.count()) << " 个/秒)" << std::endl;
// 验证分布均匀性
std::cout << "\n=== 分布均匀性验证 ===" << std::endl;
// 整数分布验证
std::map<int, int> int_buckets;
const int num_buckets = 20;
const int range_min = -1000000;
const int range_max = 1000000;
const double bucket_width = (range_max - range_min) / double(num_buckets);
for (int val : ints) {
int bucket = static_cast<int>((val - range_min) / bucket_width);
bucket = std::clamp(bucket, 0, num_buckets - 1);
int_buckets[bucket]++;
}
std::cout << "整数分布(分" << num_buckets << "个桶):" << std::endl;
double expected = total_items / double(num_buckets);
double max_deviation = 0.0;
for (int i = 0; i < num_buckets; ++i) {
double percentage = (int_buckets[i] * 100.0) / total_items;
double expected_percent = 100.0 / num_buckets;
double deviation = std::abs(percentage - expected_percent);
max_deviation = std::max(max_deviation, deviation);
std::cout << " 桶" << std::setw(2) << i << ": "
<< std::setw(8) << int_buckets[i] << " ("
<< std::fixed << std::setprecision(2) << percentage << "%)"
<< " 偏差: " << deviation << "%" << std::endl;
}
std::cout << "最大偏差: " << max_deviation << "%" << std::endl;
}
};
void test_data_generator_demo() {
std::cout << "=== 测试数据生成器 ===" << std::endl;
TestDataGenerator generator(12345); // 固定种子用于重现
// 生成边界测试用例
std::cout << "\n1. 整数边界测试用例:" << std::endl;
auto int_cases = generator.generate_boundary_cases<int>();
for (size_t i = 0; i < int_cases.size(); ++i) {
std::cout << " " << std::setw(3) << i << ": " << int_cases[i];
if ((i + 1) % 5 == 0) std::cout << std::endl;
else std::cout << " | ";
}
std::cout << "\n\n2. 浮点数边界测试用例:" << std::endl;
auto double_cases = generator.generate_boundary_cases<double>();
for (size_t i = 0; i < std::min(double_cases.size(), size_t(15)); ++i) {
std::cout << " " << std::setw(2) << i << ": "
<< std::scientific << std::setprecision(6)
<< double_cases[i] << std::endl;
}
// 生成随机数据样本
std::cout << "\n3. 随机数据样本:" << std::endl;
std::cout << " 随机整数: ";
for (int i = 0; i < 5; ++i) {
std::cout << generator.random_int(-100, 100) << " ";
}
std::cout << "\n 随机浮点数: ";
for (int i = 0; i < 5; ++i) {
std::cout << std::fixed << std::setprecision(4)
<< generator.random_double(-1.0, 1.0) << " ";
}
std::cout << "\n 随机字符串: ";
for (int i = 0; i < 3; ++i) {
std::cout << "\"" << generator.random_string(10) << "\" ";
}
std::cout << "\n 随机日期时间: ";
for (int i = 0; i < 3; ++i) {
std::cout << generator.random_datetime() << " ";
}
std::cout << "\n 随机布尔值: ";
for (int i = 0; i < 10; ++i) {
std::cout << (generator.random_bool(0.3) ? "T" : "F") << " ";
}
// 生成CSV测试文件
std::cout << "\n\n4. 生成CSV测试数据..." << std::endl;
std::vector<std::string> column_specs = {
"int", "float", "bool", "string", "datetime", "email", "phone"
};
try {
generator.generate_csv_test_data("test_data.csv", 10000, column_specs);
// 显示文件前几行
std::ifstream file("test_data.csv");
if (file.is_open()) {
std::cout << "\nCSV文件前3行内容:" << std::endl;
std::string line;
for (int i = 0; i < 4 && std::getline(file, line); ++i) {
std::cout << " " << line << std::endl;
}
file.close();
}
} catch (const std::exception& e) {
std::cerr << "错误: " << e.what() << std::endl;
}
// 性能测试
generator.performance_test(100000);
// 重现性演示
std::cout << "\n5. 重现性演示:" << std::endl;
TestDataGenerator gen1(42); // 相同种子
TestDataGenerator gen2(42); // 相同种子
TestDataGenerator gen3(43); // 不同种子
std::cout << " 生成器1 (种子42): ";
for (int i = 0; i < 5; ++i) {
std::cout << gen1.random_int(1, 100) << " ";
}
std::cout << "\n 生成器2 (种子42): ";
for (int i = 0; i < 5; ++i) {
std::cout << gen2.random_int(1, 100) << " ";
}
std::cout << "\n 生成器3 (种子43): ";
for (int i = 0; i < 5; ++i) {
std::cout << gen3.random_int(1, 100) << " ";
}
std::cout << "\n\n 结论: 相同种子产生相同序列,不同种子产生不同序列" << std::endl;
}
4. 高级主题与最佳实践
4.1 线程安全的随机数生成
在多线程环境中使用随机数需要特别注意。每个线程应该有自己的随机数生成器实例,而不是共享全局状态。
#include <random>
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <atomic>
#include <chrono>
class ThreadSafeRandom {
private:
// 线程局部存储的随机数引擎
static thread_local std::mt19937 engine;
// 初始化线程局部引擎
static void init_engine() {
static std::atomic<unsigned int> seed_counter{0};
unsigned int thread_id = std::hash<std::thread::id>{}(std::this_thread::get_id());
unsigned int time_seed = static_cast<unsigned int>(
std::chrono::high_resolution_clock::now().time_since_epoch().count());
unsigned int seed = thread_id ^ time_seed ^ (seed_counter.fetch_add(1));
engine.seed(seed);
}
public:
// 获取线程局部的引擎
static std::mt19937& get_engine() {
static thread_local bool initialized = false;
if (!initialized) {
init_engine();
initialized = true;
}
return engine;
}
// 线程安全的随机
234



被折叠的 条评论
为什么被折叠?



