【发布时间】:2017-05-24 11:25:36
【问题描述】:
作为某个游戏的代码的一部分,我想在一个向量中生成 4 个唯一的随机数。
此代码适用于一些重复播放,然后应用程序崩溃(不响应窗口)。
虽然我知道 if 条件会阻止 for 循环将相同的数字插入向量中,但这个 for 循环需要多长时间才能通过 rand() 函数生成唯一数字?
srand(time(NULL)) 和 rand() 如何精确地协同工作以根据系统时间创建随机值?
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
using namespace std;
//plays bulls and cows
int main() {
srand(time(NULL));
string play="yes";
int nums=4; // number of values in an answer (must NOT exceed 10)
vector<int> answer;
while (play=="yes" || play=="YES" || play=="Y" || play=="Yes" || play=="y") { //plays the game
answer.push_back(rand()%10+1);
do { //fills vector with unique random numbers
for (int i=1; i<nums; i++) {
answer.push_back(rand()%10+1);
if (answer[i]==answer[i-1]) {
i=i-1;
continue;
}
}
} while (answer.size()!=nums);
for (int i=0; i<nums; i++) {
cout<<answer[i];
}
cout<<"Do you want to play again?"<<'\n';
cin>>play;
answer.clear();
} //game ends
if (play=="no" || play=="n" || play=="No" || play=="NO" || play=="N") { //terminates and checks for exceptions
cout<<"Thank you for playing!"<<'\n';
return 0;
} else {
cerr<<"Error: wrong input. Terminating."<<'\n';
return 0;
}
return 0; //safety return
}
【问题讨论】:
-
另外,我知道有更好的 C++11 方法可以做到这一点,但我需要这样做。
-
考虑使用
std::set而不是std::vector。一个集合只存储唯一值:std::set<int> answer; while (answer.size() < 5) answer.insert(your_random_number); -
这很酷。但是我们现在使用向量,所以不确定它们是否会接受集合。 (运动之类的东西)
-
然后使用一个集合并将结果复制到您的向量中。无需编写容易出错的循环。
-
@PaulMcKenzie,这是一种方法。谢谢。