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 函数接收两个参数 ab,它们都是 pair<char, int> 类型,分别代表一个字符和它的出现次数。

cmp 函数的目的是根据字符出现次数和 ASCII 码对字符进行排序。具体逻辑如下:

  • 比较次数: 首先,比较 absecond 成员,即字符出现的次数。如果 a 的次数大于 b 的次数,则返回 true,表示 a 应该排在 b 前面;如果 a 的次数小于 b 的次数,则返回 false,表示 a 应该排在 b 后面;如果次数相等,则进行下一步比较。

  • 比较 ASCII 码: 如果次数相等,则比较 abfirst 成员,即字符的 ASCII 码。如果 a 的 ASCII 码小于 b 的 ASCII 码,则返回 true,表示 a 应该排在 b 前面;否则返回 false

3. 代码解释

  1. pair<char, int> charCount[128] 定义一个大小为 128 的 pair 数组,用于存储每个字符及其出现次数。
  2. memset(charCount, 0, sizeof(charCount)) 使用 memset 函数将 charCount 数组初始化为 0。
  3. for (int i = 0; str[i] != '0'; i++) 循环遍历输入字符串,统计每个字符出现的次数。
  4. sort(charCount, charCount + 128, cmp) 使用 sort 函数对 charCount 数组进行排序,并传入自定义比较函数 cmp
  5. for (int i = 0; i < 128; i++) 循环遍历排序后的 charCount 数组,输出出现次数最多的字符。

总结

本代码使用 C++ 中的 sort 函数和自定义比较函数 cmp 对字符串中的字符进行计数排序。 cmp 函数用于根据字符出现次数和 ASCII 码对字符进行排序,并通过 sort 函数进行排序。代码示例和解释可以帮助读者更好地理解该算法。

希望这篇文章能够帮助您理解 C++ 中的 sort 函数和自定义比较函数的使用方法。

C++ 字符计数排序:使用自定义比较函数cmp

原文地址: https://www.cveoy.top/t/topic/nYCq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录