检查数组中的重复数

Checking Duplicates Numbers In Array c++

本文关键字:数组 检查      更新时间:2023-10-16

我写了一个简单的c++程序来查找数组中有多少个重复项。

这对我来说是完美的,但这是很长的代码。我想知道是否有任何短代码可以成功执行此任务:

#include<iostream>
using namespace std;
int main()
{
int a[10];
int reper=0,word=0,flage=0,number[10]={
    0
};
//Getting Input From User
for (int i = 0; i <=9; i++)
{
    cout<<"Enter The Value For "<<i<<" Index"<<endl;
    cin>>a[i];
}
//Checking The Duplicates Numbers
for (int i = 0; i <= 9; i++)
{
    reper=0;
    flage=0;
    for (int j = 0; j <=9; j++)
    {
        if (a[i]==a[j])
        {
            if (i!=j)
            {
                reper++;
            }
        }
    }
    number[i]=a[i];
    for (int k = 0; k <=9; k++)
    {
        if (i!=k)
        {
            if(number[i]==number[k])
            {
            flage=1;
            break;
            }
        }
    }
    //If There Are Duplicates Then Prints That Numebr, How Many Times It Repeated And Total Occurance Of That Number In The Array
    if (reper!=0&&flage==0)
    {
        cout<<"Repeated Number Of The Array Is  : "<<a[i]<<" ";
        cout<<"And This Number Repeated "<<reper<<" Times "<<"And Total Occurance Of This Number is : "<<reper+1<<endl;
        word=a[i];
    }
}
//If There Is Nothing Any Duplicate In The Array Then Simply Prints This Message On Console
if (reper==0&&word==0)
{
    cout<<"There Is Nothing Any Repeated Number Of This Array: "<<endl;
}
system("Pause");
return 0;
}

我认为实现这个最简单的方法-使用http://en.cppreference.com/w/cpp/container/multiset。它具有对数复杂度和内部方法来计数重复项目。参考下面的示例:

#include <iostream>
#include <set>
int main(int argc, char *argv[])
{
    std::multiset<int> ms;
    //Getting Input From User
    for (int i = 0; i <=9; i++)
    {
        std::cout<<"Enter The Value For "<<i<<" Index"<<std::endl;
        int val;
        std::cin>>val;
        ms.insert(val);
    }
    bool repeated_number_found=false;
    std::multiset<int>::const_iterator it = ms.begin();
    while (it != ms.end()) {
        int reper=ms.count(*it);
        if (reper > 1){
            std::cout << "Number " << *it << " repeated for " << reper << " times" << std::endl;
            repeated_number_found=true;
        }
        it = ms.upper_bound(*it);
    }
    if (!repeated_number_found){
        std::cout<<"There Is Nothing Any Repeated Number Of This Array"<<std::endl;
    }
    return 0;
}

但是使用这个容器你会丢失重复的数字的第一个入口,如果它对你很重要,我建议使用struct或std::pair来保存输入的数字的入口编号。在这种情况下,您还需要提供自定义比较器(参考文档)

我认为更好的方法是对数组进行排序,并做这样的事情:-

(在此之前包括头文件算法)

vector <int> a (10,0);
for (int i = 0; i <=9; i++)
{
  cout<<"Enter The Value For "<<i<<" Index"<<endl;
  cin>>a[i];
}
int count = 0;
sort(a.begin(), a.end());
for(int i = 0; i < a.size() - 1; i++) {
if (a[i] == a[i + 1]) {
    count++;
   }
}
cout << count << endl;