检查数组中的重复数
Checking Duplicates Numbers In Array c++
我写了一个简单的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;
相关文章:
- 试图让变量检查数组中的某些内容
- 如何在C++中检查2D数组中负值的输入验证
- 使用for循环检查数组中的重复项
- 检查TCHAR数组输入是否为带符号整数C++
- std::数组边界检查如何工作?
- 检查输入 std::array 指针数据是否等于某个常量数组
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- C++ 检查结果数组中有多少次数字
- 检查数组中是否有字符串中的值,如果没有,则添加它
- 有没有办法在c ++中清除空数组,请检查下面的代码以获取说明
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- 如何检查二维数组上的周围数字?
- 检查反向数组是否与原始数组相同
- 如何检查cin是否与数组中的一组数字匹配
- 如何检查数组中是否没有值
- 如何检查字节数组是protobuf序列化字节数组还是普通字节数组
- 检查彩虹数组(检查数组的反向样式是否与自身匹配)
- 使用数组检查连续性
- c++ 根据随机生成的数组检查用户输入的值
- 使用字符串数组检查用户输入