【发布时间】:2020-07-09 10:31:01
【问题描述】:
我正在编写一个没有重复的随机名称生成器。我想在没有像 algorithm 之类的其他库的情况下做到这一点,因为我想了解如何做到这一点。有没有办法用循环或向量来做到这一点?
我想将已经存在的名称添加到向量中,然后使用 while 循环检查向量的所有元素,但我不知道该怎么做。
#include <windows.h>
#include <conio.h>
#include <vector>
#include <ctime>
#include <iostream>
#include <ctime>
using namespace std;
int main() {
srand((unsigned)time(0));
int names = 1;
int a = 0;
int x = 0;
vector <string> vectornames;
cout << "How many names would you like to add: ";
int amount_of_names;
cin >> amount_of_names;
while (a < amount_of_names) {
cout << "Enter name " << names << ": ";
string name;
cin >> name;
vectornames.push_back(name);
names++;
a++;
}
while (x < amount_of_names) {
cout << "\n" << vectornames.at(x);
x++; }
cout << "\npress enter to continue: ";
getch();
system("cls");
int z = 0;
while (z < amount_of_names) {
int random_number = (rand() % amount_of_names);
if (vectornames.at(random_number) != vectornames.at(z)) {
cout << "Hello ";
cout << vectornames.at(z);
cout << "! You will get " << vectornames.at(random_number) << "\n";
vectornames.push_back(vectornames.at(random_number));
getch();
z++;
}}
cout << "\n\n";
return 0;
}
【问题讨论】:
-
也许是
std::unordered_set的字母?循环生成,直到获得所需的长度。并且请不要使用srand和rand,一定有更好的classes available in the standard library。 -
完成后,用
1, 2, 3, 4 ...之类的数字序列填充vector<int>,然后随机填充swap元素。您现在有一个随机的数字序列可供选择。int random_number = vec.back(); vec.pop_back();(直到vector为空)。 -
您可以使用<random> 和random_shuffle 对数字向量进行洗牌。
-
@Ususwoa
<algorithm>和<random> 和其他人是标准库的一部分,就像<vector>一样。 -
为什么
rand()被允许,即使它经常被建议避免它并且random是不允许的?
标签: c++ loops vector while-loop