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

问题描述

我写在C ++这个code作为一个单任务,我需要保证有一个阵列内没有重复的一部分:

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数组进行排序(n日志(N)),然后简单地看,直到下一个号码。这比你为O(n ^ 2)对现有的算法快得多。在code也是很多清洁。他们再次进入时,您的code也不能保证没有重复插入。您需要从现有的摆在首位prevent重复。

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.at(i))
        i--;
    }
}

我也是第二个reccomendation使用一个std ::集 - 没有重复出现。

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

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

08-19 13:06