我有一个给定的数组,我需要确定如何在其中查找重复项的数量。我必须使用嵌套的for循环来执行此操作,并且不能使用向量。到目前为止,我已经尝试过了,得到3,但是答案应该是2,因为只有数字4和7重复了。我知道为什么我得到3,因为它两次检查4,但是我似乎无法弄清楚如何调整它,所以一旦找到匹配项就再也不会检查4。

#include <iostream>
using namespace std;

int main() {
    const int num_elements = 12;
    int numbers[num_elements] = { 2, 6, 7, 4, 5, 4, 1, 8, 9, 0, 7, 4 };

    unsigned int numduplicates = 0;
    for(int i = 0; i < num_elements; ++i){
        int oneCounterMax = 0;
        for(int j = i + 1; j < num_elements; ++j) {
            if((numbers[i] == numbers[j]) && (oneCounterMax < 1)) {
                ++numduplicates;
                ++oneCounterMax;
            }

        }
    }
    cout << numduplicates << endl;
}

最佳答案

最好的方法是使用std::vectorstd::map,正如其他人已经提到的那样。但是由于您只能使用嵌套循环和数组,因此下面的示例有效:

const int num_elements = 12;
int numbers[num_elements] = { 2, 6, 7, 4, 5, 4, 1, 8, 9, 0, 7, 4 };
int counter = 0;

for ( int i = 0; i < num_elements; i++ ) {
    for ( int j = i + 1; j < num_elements; j++ ) {
        if ( numbers[j] == numbers[i] ) {
            counter++;
            for ( int k = 0; k < i; k++ ) {
                if ( numbers[k] == numbers[j] ) {
                    counter--;
                    break;
                }
            }
            break;
        }
    }
}

cout << counter << endl;


它将打印2,而不是3。简而言之,当我们找到一个重复项时,我们返回并检查是否已经达到此数字。

关于c++ - 如何查找数组中的重复项数量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36312913/

10-11 22:23
查看更多