该程序应该让用户输入5个名称并输出任何重复的名称。如何使程序输出数组内值的"重复名称"?我似乎不明白如何编写它,因此当用户输入名称时,它会检查重复的元素。谢谢。
#include <iostream>
using namespace std;
int main() {
string names[5]; //array with 5 names
string input;
for (string input : names){
cout << "Please enter a name: ";
cin >> input;
}
for (int check = 1; check-1; check++){
if (input == names[check]){
cout << input << " is a duplicate name!" << endl;
}
}
}
需要纠正的一些问题包括:
for (string input : names)
创建一个临时变量,并且无法修改原始数组;使用for (string &input : names)
创建对循环块中每个数组元素的引用。- 您的
for
循环不是嵌套的,因此没有理由将数组的某些元素(或input
字符串(与其他元素进行比较。将第二个循环嵌套在input
循环中,以便在添加名称时执行检查,或者将检查分离到其自己的块中。请注意,有更有效的方法可以解决此问题,例如保留您见过的名字unordered_set
;嵌套循环的时间复杂度呈指数级增长。 - 您的第二个
for
循环的终止条件并没有测试任何有用的东西(它计算为0
哪个是false
,立即终止循环(。迭代直到计数器达到或超过数组的长度5
更合适。
#include <iostream>
int main() {
std::string names[5];
for (std::string &input : names) {
std::cout << "Please enter a name: ";
std::cin >> input;
}
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
if (names[i] == names[j]){
std::cout << names[i] << " is a duplicate name!" << std::endl;
}
}
}
}
输出:
Please enter a name: a
Please enter a name: b
Please enter a name: c
Please enter a name: d
Please enter a name: a
a is a duplicate name!
试试吧