C++ 字符统计:利用sort和自定义比较函数cmp
C++ 字符统计:利用sort和自定义比较函数cmp
本文将介绍使用 C++ 中的 sort 函数和自定义比较函数 cmp 来统计字符串中字符出现次数的代码实现。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
bool cmp(pair<char, int> a, pair<char, int> b) {
if (a.second == b.second) {
return a.first < b.first;
} else {
return a.second > b.second;
}
}
void countChars(char* str) {
pair<char, int> charCount[128];
memset(charCount, 0, sizeof(charCount));
for (int i = 0; str[i] != '0'; i++) {
charCount[str[i]].first = str[i];
charCount[str[i]].second++;
}
sort(charCount, charCount + 128, cmp);
for (int i = 0; i < 128; i++) {
if (charCount[i].second != 0) {
cout << charCount[i].first;
}
}
}
int main() {
char str[100];
cin >> str;
countChars(str);
return 0;
}
在这个代码中,cmp 函数的本体内容如下:
bool cmp(pair<char, int> a, pair<char, int> b) {
if (a.second == b.second) {
return a.first < b.first;
} else {
return a.second > b.second;
}
}
这个 cmp 函数是用来作为 sort 函数的比较函数,用来比较两个 pair<char, int> 类型的元素大小关系。具体来说,如果它们的 second 相等,则按照 first 的字典序进行比较;否则,就按照 second 的大小关系进行比较。
代码逻辑流程:
- 初始化一个大小为 128 的
pair<char, int>数组charCount,用来存储字符及其出现次数。 - 遍历字符串
str,统计每个字符出现的次数,并存储在charCount数组中。 - 使用
sort函数对charCount数组进行排序,并使用cmp函数作为比较函数。 - 输出排序后的
charCount数组中所有出现次数不为 0 的字符。
总结:
本文介绍了使用 C++ 中的 sort 函数和自定义比较函数 cmp 来统计字符串中字符出现次数的代码实现。详细解释了 cmp 函数的原理和作用,以及代码的逻辑流程。希望这篇文章对你有所帮助。
站长合作邮箱:wxgpt@qq.com
原文地址: https://www.cveoy.top/t/topic/nYCu 著作权归作者所有。请勿转载和采集!