方法一:传统遍历+哈希表(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
或其他动态容器,以便处理不同大小的数据。上述示例展示了如何对整型数组进行统计,其中方法一是最通用且适应性最强的方式。