在 C++ 中重复数组中的整数元素的次数

how many times repeat integer elements in array in C++

本文关键字:整数 元素 数组 C++      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main()
{
setlocale(LC_ALL,"Turkish");
int dizi[10]={9,30,3,6,9,20,3,6,10,9};
int counter, j;
for(int i=0; i<10; i++){
counter=1;
for(int j=i+1; j<10;  j++){
if(dizi[i]==dizi[j+1]){
counter++;
}   
}
cout<<dizi[i]<<"t:"<<counter<<endl;        
}
}
/*
//THE RESULT
9       :3   
30      :1   
3       :2   
6       :2   
9       :2   //WRONG I don't want this line to appear
20      :1   
3       :1   //WRONG I don't want this line to appear
6       :1   //WRONG I don't want this line to appear
10      :1   
9       :1   //WRONG I don't want this line to appear
*/

我更喜欢使用STL来解决此类问题。遍历数组,以counts计算出现次数,并将顺序存储在order中。

#include <iostream>
#include <unordered_map>
#include <vector>
int main() 
{
int dizi[] = { 9, 30, 3, 6, 9, 20, 3, 6, 10, 9 };
std::unordered_map<int, std::size_t> counts;
std::vector<int> order;
for (const auto &el : dizi) {
if (counts.find(el) == counts.end()) order.push_back(el);
++counts[el];
}
for (const auto &el : order) {
std::cout << el << "t:" << counts[el] << 'n';
}
return 0;
}

输出:

9   :3
30  :1
3   :2
6   :2
20  :1
10  :1

看来你的意思是以下几点

#include <iostream>
int main() 
{
int dizi[] = { 9, 30, 3, 6, 9, 20, 3, 6, 10, 9 };
const size_t N = sizeof( dizi ) / sizeof( *dizi );
for ( size_t i = 0; i < N; i++ )
{
size_t j = 0;
while ( j != i && dizi[j] != dizi[i] ) ++j;
if ( j == i )
{
size_t counter = 1;
while ( ++j != N )
{
if ( dizi[j] == dizi[i] ) ++counter;
}
std::cout << dizi[i] << ":t" << counter << 'n';
}
}
return 0;
}

程序输出为

9:  3
30: 1
3:  2
6:  2
20: 1
10: 1

也就是说,您需要检查当前值是否已被抵消。