C++ 字符统计排序代码分析:cmp 函数详解
C++ 字符统计排序代码分析:cmp 函数详解
这段 C++ 代码实现了字符统计并按照出现次数和字母顺序进行排序的功能。代码的核心部分在于 cmp 函数,它作为 sort 函数的比较器,负责比较两个 pair<char, int> 类型元素的大小。
#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;
}
}
// ...
cmp 函数的解析:
cmp函数接受两个pair<char, int>类型参数a和b,分别代表两个字符及其出现次数的组合。- 首先,
cmp函数比较a.second和b.second,即比较两个字符的出现次数。如果a.second大于b.second,则表示字符a出现的次数更多,cmp函数返回true;反之,如果a.second小于b.second,则返回false。 - 如果
a.second和b.second相等,则比较a.first和b.first,即比较两个字符的字母顺序。如果a.first小于b.first,则表示字符a在字母表中排在前面,cmp函数返回true;反之,返回false。
总结:
cmp 函数的功能是根据字符出现次数和字母顺序对字符进行排序,从而实现对输入字符串中所有字符的统计和排序。在实际应用中,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 函数在 C++ 中的应用和功能。
原文地址: https://www.cveoy.top/t/topic/nYCt 著作权归作者所有。请勿转载和采集!