如何计算2d数组中的重复数?(C++)
How to count the number of duplicates in a 2d array? (C++)
大家怎么了,我必须创建一个算法,创建一个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]){
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '