首页 > 解决方案 > 在不使用 std::vector 及其特性的情况下防止元素重复

问题描述

我有一个程序要求用户输入 ID 并输入名称。但是,该 ID 必须是唯一的,以便用户可以继续输入姓名,否则程序必须不断提示用户输入唯一的 ID。

问题是,尽管用户输入了一个唯一的字符串,但程序仍然不断提示用户输入 ID,因此输入名称的代码永远不会执行。

#include <iostream>

int main() {
    std::string ID = {};
    std::string copy[3] = {};
    std::string name = {};
    bool isDuplicated = false;

    for (int i = 0; i < 3; ++i) {
        std::cout << "Enter details for student " << i + 1 << ": " << '\n';
        tryAgain:
        std::cout << "Enter ID: ";
        std::cin >> ID;

        // If ID is not duplicated,
        // continue to code of entering name. Otherwise,
        // keep prompting the user to enter a unique ID.

        for (int i = 0; i < 3; ++i) {
            if (i != 0)
                copy[i] = ID;

            if (copy[i] == ID) {
                isDuplicated = true;
                std::cout << "ERROR" << '\n';
            }
        }

        if (isDuplicated)
            goto tryAgain;

        else {
            std::cout << "Enter name: ";
            std::cin >> name;
            std::cout << '\n';
        }
    }
 
    return 0;
}

需要的输出(示例模拟):

Enter details for student 1:
Enter ID: 13
Enter name: Dog

Enter details for student 2:
Enter ID: 13 
ERROR: You already entered the ID!
Enter ID again: 17    
Enter name: Cat

Enter details for student 3:
Enter ID: 21
Enter name: Mouse

我的程序输出什么:

Enter details for student 1:
Enter ID: 13
ERROR: You already entered the ID!
ERROR: You already entered the ID!
Enter ID: 17
ERROR: You already entered the ID!
ERROR: You already entered the ID!

请注意,我们不能使用 std::vector 及其特性,这是我们需要坚持使用自己编写的算法的原因。

任何帮助表示赞赏。非常感谢!

标签: c++arraysalgorithm

解决方案


copy[i] = ID;

绝对保证

if (copy[i] == ID) 

会找到重复的。

ID解决方案:在验证没有重复之前不要放入阵列中。


推荐阅读