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> 类型参数,分别代表两个要比较的字符及其出现次数。
  • 函数内部首先比较两个 pairsecond 成员,即字符出现次数。如果次数相同,则比较 first 成员,即字符的字典序。
  • 返回值:如果 a 应该排在 b 前面,则返回 true;否则返回 false

排序流程:

  1. 代码使用 sort 函数对 charCount 数组进行排序,并传入 cmp 函数作为比较函数。
  2. sort 函数会根据 cmp 函数的返回值来决定如何排序,最终实现根据字符出现次数从大到小排序,如果出现次数相同,则按照字典序从小到大排序。

总结:

cmp 函数是 C++ 字符统计排序算法中的关键部分,它定义了排序规则,使程序能够有效地对字符出现次数进行排序。通过使用自定义比较函数,我们可以根据不同的需求进行排序,实现灵活的排序功能。

C++ 字符统计排序算法:cmp 函数解析

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

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