答案:程序实现抽奖系统,支持添加、删除、显示参与者及随机抽取中奖者。使用vector管理名单并检查重复,依托random_device和mt19937生成安全随机数,通过uniform_int_distribution获取有效下标,确保高效公平抽取,结构清晰可扩展。

实现一个C++抽奖程序,关键在于随机选择与名单管理。程序需要支持添加、删除、显示参与者,并能从中随机抽取一人或多个人。下面是一个简洁、实用的实现方案,适合学习或实际使用。
程序主要包含以下功能:
使用 std::random_device 和 std::mt19937 生成高质量随机数,避免使用简单的 rand() % n,提高随机性。
立即学习“C++免费学习笔记(深入)”;
从名单中随机抽取时,使用下标访问 vector 元素,确保效率。
示例代码片段:
#include <random> std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, names.size() - 1); int index = dis(gen); std::cout << "中奖者: " << names[index] << std::endl;
使用 std::vector<std::string> 存储参与者姓名,支持动态增删。
添加姓名直接 push_back;删除时遍历查找并使用 erase 移除。
可添加重复姓名检查,避免同一人多次参与:
以下是一个控制台版本的简要实现框架:
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <algorithm>
<p>int main() {
std::vector<std::string> participants;
std::random_device rd;
std::mt19937 gen(rd());</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">while (true) {
std::cout << "\n1. 添加 2. 删除 3. 显示 4. 抽奖 0. 退出: ";
int choice; std::cin >> choice;
if (choice == 1) {
std::string name;
std::cout << "输入姓名: "; std::cin >> name;
if (std::find(participants.begin(), participants.end(), name) == participants.end()) {
participants.push_back(name);
std::cout << "添加成功\n";
} else {
std::cout << "该姓名已存在\n";
}
}
else if (choice == 2) {
std::string name;
std::cout << "输入要删除的姓名: "; std::cin >> name;
auto it = std::find(participants.begin(), participants.end(), name);
if (it != participants.end()) {
participants.erase(it);
std::cout << "删除成功\n";
} else {
std::cout << "未找到该姓名\n";
}
}
else if (choice == 3) {
std::cout << "当前名单:\n";
for (const auto& n : participants) std::cout << n << " ";
std::cout << std::endl;
}
else if (choice == 4) {
if (participants.empty()) {
std::cout << "名单为空!\n";
} else {
std::uniform_int_distribution<> dis(0, participants.size() - 1);
std::cout << "恭喜 " << participants[dis(gen)] << " 中奖!\n";
}
}
else if (choice == 0) break;
}
return 0;}
基本上就这些。结构清晰,易于扩展,比如支持批量抽奖、保存名单到文件等。核心是随机性和名单操作的正确实现。
以上就是C++抽奖程序实现 随机选择名单管理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号