首页 > 文章列表 > 如何正确使用C++sort函数实现定制排序功能

如何正确使用C++sort函数实现定制排序功能

sort c++
482 2024-04-02

sort 函数利用自定义比较函数实现定制排序:编写比较函数:指定排序规则,定义参数类型和返回值。调用 sort 函数:将自定义比较函数作为第三个参数,对容器中的元素进行排序。示例:按降序对整数排序,按自定义规则对字符串排序(空字符串优先、长度优先、字典序优先)。

如何在 C++ 中使用 sort 函数实现定制排序功能

sort 函数是 C++ 标准库中的一个重要函数,用于对容器中的元素进行排序。它以引用方式接收一个比较函数,允许用户根据自定义条件对元素进行排序。

比较函数的语法

比较函数的语法如下:

bool compare(const T1& a, const T2& b);

其中:

  • T1T2 是要比较的元素类型。
  • 返回 true 表示 a 小于 b
  • 返回 false 表示 a 大于或等于 b

实现定制排序

要使用 sort 函数实现定制排序,您需要编写一个指定排序行为的自定义比较函数。以下是一个示例:

#include <algorithm>
#include <vector>

using namespace std;

bool compareIntsDescending(int a, int b) {
  return a > b;
}

int main() {
  vector<int> numbers = {1, 5, 2, 4, 3};

  sort(numbers.begin(), numbers.end(), compareIntsDescending);

  for (auto& num : numbers) {
    cout << num << " ";
  }
  cout << endl;

  return 0;
}

这个程序的输出:

5 4 3 2 1

在这个例子中,compareIntsDescending 比较函数将整数从大到小进行排序。

实战案例:按自定义规则对字符串排序

假设您有一个字符串数组,您希望按以下规则对其进行排序:

  • 空字符串先排序。
  • 较长的字符串先排序(长度相同时按字母顺序排序)。

您可以编写以下比较函数来实现此功能:

bool compareStrings(string a, string b) {
  // 检查是否为空字符串
  if (a.empty() && !b.empty()) {
    return true;
  } else if (!a.empty() && b.empty()) {
    return false;
  }

  // 空字符串相等
  if (a.empty() && b.empty()) {
    return false;
  }

  // 比较长度
  if (a.length() < b.length()) {
    return true;
  } else if (a.length() > b.length()) {
    return false;
  }

  // 长度相同时按字母顺序比较
  return (a < b);
}

然后,您可以使用此比较函数对字符串数组进行排序,如下所示:

#include <algorithm>
#include <vector>

using namespace std;

int main() {
  vector<string> strings = {"apple", "banana", "cherry", "dog", "cat", ""};

  sort(strings.begin(), strings.end(), compareStrings);

  for (auto& str : strings) {
    cout << str << " ";
  }
  cout << endl;

  return 0;
}

这个程序的输出:

 dog cat apple banana cherry