C++ 字符统计排序算法:cmp 函数解析
C++ 字符统计排序算法:cmp 函数解析
在这个代码中,cmp 是一个用于排序的自定义比较函数,用于比较存储字符和字符出现次数的 pair 类型数组中的元素。具体来说,它按照字符出现次数从大到小排序,如果字符出现次数相同,则按照字符的字典序从小到大排序。
代码示例:
#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 函数解析:
cmp函数接受两个pair<char, int>类型参数,分别代表两个要比较的字符及其出现次数。- 函数内部首先比较两个
pair的second成员,即字符出现次数。如果次数相同,则比较first成员,即字符的字典序。 - 返回值:如果
a应该排在b前面,则返回true;否则返回false。
排序流程:
- 代码使用
sort函数对charCount数组进行排序,并传入cmp函数作为比较函数。 sort函数会根据cmp函数的返回值来决定如何排序,最终实现根据字符出现次数从大到小排序,如果出现次数相同,则按照字典序从小到大排序。
总结:
cmp 函数是 C++ 字符统计排序算法中的关键部分,它定义了排序规则,使程序能够有效地对字符出现次数进行排序。通过使用自定义比较函数,我们可以根据不同的需求进行排序,实现灵活的排序功能。
原文地址: https://www.cveoy.top/t/topic/nYCo 著作权归作者所有。请勿转载和采集!