更优雅的方法来检查 C++ 数组中的重复项? [英] More elegant way to check for duplicates in C++ array?

查看:30
本文介绍了更优雅的方法来检查 C++ 数组中的重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 C++ 编写了这段代码,作为 uni 任务的一部分,我需要确保数组中没有重复项:

I wrote this code in C++ as part of a uni task where I need to ensure that there are no duplicates within an array:

// Check for duplicate numbers in user inputted data
    int i; // Need to declare i here so that it can be accessed by the 'inner' loop that starts on line 21
    for(i = 0;i < 6; i++) { // Check each other number in the array
        for(int j = i; j < 6; j++) { // Check the rest of the numbers
            if(j != i) { // Makes sure don't check number against itself
                if(userNumbers[i] == userNumbers[j]) {
                    b = true;
                }
            }
            if(b == true) { // If there is a duplicate, change that particular number
                cout << "Please re-enter number " << i + 1 << ". Duplicate numbers are not allowed:" << endl;
                cin >> userNumbers[i];
            }
        } // Comparison loop
        b = false; // Reset the boolean after each number entered has been checked
    } // Main check loop

它工作得很好,但我想知道是否有更优雅或更有效的检查方法.

It works perfectly, but I'd like to know if there is a more elegant or efficient way to check.

推荐答案

您可以按 O(nlog(n)) 对数组进行排序,然后只需查找下一个数字即可.这比您的 O(n^2) 现有算法快得多.代码也干净了很多.您的代码也不能确保在重新输入时没有插入重复项.您首先需要防止重复.

You could sort the array in O(nlog(n)), then simply look until the next number. That is substantially faster than your O(n^2) existing algorithm. The code is also a lot cleaner. Your code also doesn't ensure no duplicates were inserted when they were re-entered. You need to prevent duplicates from existing in the first place.

std::sort(userNumbers.begin(), userNumbers.end());
for(int i = 0; i < userNumbers.size() - 1; i++) {
    if (userNumbers[i] == userNumbers[i + 1]) {
        userNumbers.erase(userNumbers.begin() + i);
        i--;
    }
}

我还推荐使用 std::set - 那里没有重复项.

I also second the reccomendation to use a std::set - no duplicates there.

这篇关于更优雅的方法来检查 C++ 数组中的重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆