怎么统计一个数组中每个元素的数量?

方法一:传统遍历+哈希表(std::unordered_map

Cpp

#include <iostream>
#include <unordered_map>

void countElements(int arr[], int n) {
    std::unordered_map<int, int> counts;
    for (int i = 0; i < n; ++i) {
        counts[arr[i]]++;
    }

    // 输出每个元素及其出现次数
    for (const auto &entry : counts) {
        std::cout << "Element: " << entry.first << ", Count: " << entry.second << '\n';
    }
}

int main() {
    int arr[] = {1, 2, 3, 1, 2, 4, 5, 1, 2};
    int n = sizeof(arr) / sizeof(arr[0]);

    countElements(arr, n);

    return 0;
}

方法二:使用标准库算法std::count_if配合Lambda表达式

Cpp

#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>

int main() {
    std::vector<int> vec = {1, 2, 3, 1, 2, 4, 5, 1, 2};

    std::unordered_map<int, int> counts;

    // 对于vector,可以直接用迭代器
    for (auto it = vec.begin(); it != vec.end(); ++it) {
        counts[*it]++;
    }

    // 或者使用std::count_if配合lambda表达式,但这种方式需要多次调用,对于非连续的整数集不太适用
    for (int i = 0; i <= *vec.rbegin(); ++i) {
        counts[i] += std::count_if(vec.begin(), vec.end(), [i](int x) { return x == i; });
    }

    // 输出结果
    for (const auto &entry : counts) {
        if (entry.second > 0) {
            std::cout << "Element: " << entry.first << ", Count: " << entry.second << '\n';
        }
    }

    return 0;
}

方法三:基于排序后相邻元素比较(仅适用于有序数组或对结果排序无影响的情况)

Cpp

#include <iostream>
#include <vector>
#include <algorithm>

void countElements(std::vector<int>& vec) {
    std::sort(vec.begin(), vec.end());
    
    int current = vec[0];
    int count = 1;

    for (size_t i = 1; i < vec.size(); ++i) {
        if (vec[i] == current) {
            ++count;
        } else {
            std::cout << "Element: " << current << ", Count: " << count << '\n';
            current = vec[i];
            count = 1;
        }
    }
    // 输出最后一个元素的计数
    std::cout << "Element: " << current << ", Count: " << count << '\n';
}

int main() {
    std::vector<int> vec = {1, 2, 3, 1, 2, 4, 5, 1, 2};
    countElements(vec);

    return 0;
}

        在实际应用中,通常数组会存储为std::vector或其他动态容器,以便处理不同大小的数据。上述示例展示了如何对整型数组进行统计,其中方法一是最通用且适应性最强的方式。

  • 21
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值