如何计算2d数组中的重复数?(C++)

How to count the number of duplicates in a 2d array? (C++)

本文关键字:C++ 数组 何计算 计算 2d      更新时间:2023-10-16

大家怎么了,我必须创建一个算法,创建一个5x5数组,数组中填充从0到9的随机数,然后计算每个数字在数组中出现的次数。我的基本代码如下:

#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
int i,j,a=0;
int tab[5][5];
for (i=0;i<5;i++)
{
for (j=0;j<5;j++)
{
tab[i][j] = rand()%10;
cout << tab[i][j] << "|";
}
}
return 0;
}

现在我不知道如何做第二部分。我只需要创建10个新整数并使用蛮力即可,但我希望代码看起来更干净、更高效。有什么想法吗?

您可以使用哈希。矢量的第i个索引包含i的频率。

像这样的东西。

vector<int> getFreq(size_t rows, size_t cols, int **a) {
vector<int> ans(9);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
ans[a[i][j]]++;
}
}
return ans;
}

std::unordereded_map是解决问题的好方法。以下函数模板将完成您的工作。请注意,@aaijmrt提供的解决方案并不是真正的哈希,当你生成更大范围(比如从0到10000000(的随机数时,它也不会有效。

template<typename Key, std::size_t rows, std::size_t cols>
std::unordered_map<Key, size_t> countFrequency(Key Arr[rows][cols], Key(&)[rows][cols]){
std::unordered_map<Key,size_t> freq;
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
Key k = *((*Arr+i*cols)+j);
if(freq.find(k)!=freq.end())
freq[k] = freq[k]+1;
else
freq.insert({k,1});
}
}
return freq;
}

像这个一样调用上面的函数

auto freq = countFrequency(tab, tab);
for(const auto elem : freq) std::cout<<elem.first<<" "<<elem.second<<"n";

模板机械只是为了方便,你可以像这个一样去掉它

std::unordered_map<int, size_t> countFrequency(size_t rows, size_t cols, int Arr[5][5]){