C++ 字符计数排序:使用自定义比较函数cmp
C++ 字符计数排序:使用自定义比较函数cmp
本文将深入探讨使用 C++ 中的 sort 函数和自定义比较函数 cmp 对字符串中的字符进行计数排序。 cmp 函数用于根据字符出现次数和 ASCII 码对字符进行排序,并展示了代码示例和详细解释。
1. 代码示例
#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;
}
2. cmp 函数详解
cmp 是一个自定义的比较函数,它用于 sort 函数中对 pair 类型的元素进行排序。cmp 函数接收两个参数 a 和 b,它们都是 pair<char, int> 类型,分别代表一个字符和它的出现次数。
cmp 函数的目的是根据字符出现次数和 ASCII 码对字符进行排序。具体逻辑如下:
-
比较次数: 首先,比较
a和b的second成员,即字符出现的次数。如果a的次数大于b的次数,则返回true,表示a应该排在b前面;如果a的次数小于b的次数,则返回false,表示a应该排在b后面;如果次数相等,则进行下一步比较。 -
比较 ASCII 码: 如果次数相等,则比较
a和b的first成员,即字符的 ASCII 码。如果a的 ASCII 码小于b的 ASCII 码,则返回true,表示a应该排在b前面;否则返回false。
3. 代码解释
pair<char, int> charCount[128]: 定义一个大小为 128 的pair数组,用于存储每个字符及其出现次数。memset(charCount, 0, sizeof(charCount)): 使用memset函数将charCount数组初始化为 0。for (int i = 0; str[i] != '0'; i++): 循环遍历输入字符串,统计每个字符出现的次数。sort(charCount, charCount + 128, cmp): 使用sort函数对charCount数组进行排序,并传入自定义比较函数cmp。for (int i = 0; i < 128; i++): 循环遍历排序后的charCount数组,输出出现次数最多的字符。
总结
本代码使用 C++ 中的 sort 函数和自定义比较函数 cmp 对字符串中的字符进行计数排序。 cmp 函数用于根据字符出现次数和 ASCII 码对字符进行排序,并通过 sort 函数进行排序。代码示例和解释可以帮助读者更好地理解该算法。
希望这篇文章能够帮助您理解 C++ 中的 sort 函数和自定义比较函数的使用方法。
原文地址: https://www.cveoy.top/t/topic/nYCq 著作权归作者所有。请勿转载和采集!