21xrx.com
2025-06-20 05:37:38 Friday
文章检索 我的文章 写文章
C++排序函数用法
2023-06-30 16:25:59 深夜i     21     0
C++ 排序函数 用法

C++是一种强大的编程语言,有许多内置的排序函数,可以帮助程序员轻松地对数组、列表和其他数据结构进行排序。本文将介绍C++中几个常用的排序函数。

1. std::sort

std::sort函数是C++中最常用的排序函数之一,它可以对数组、列表或迭代器范围内的元素进行排序。其语法如下:

std::sort(first, last, compare);

其中,first和last是迭代器范围,表示待排序元素的区间,compare是可选的比较函数,用于比较元素的大小关系。如果不提供比较函数,则默认采用升序排序。

下面是一个示例代码,演示如何使用std::sort函数对整数数组进行降序排序:

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
  int arr[] = 10;
  int n = sizeof(arr) / sizeof(arr[0]);
  std::sort(arr, arr + n, greater<int>()); // 按降序排列
  for (int i = 0; i < n; ++i) {
    cout << arr[i] << " ";
  }
  return 0;
}

2. std::stable_sort

std::stable_sort函数是一个稳定的排序函数,与std::sort类似,它也可以按照指定的比较函数对元素进行排序。不同之处在于,std::stable_sort会保持相等元素的相对顺序,即使它们的值相同。其语法与std::sort相似:

std::stable_sort(first, last, compare);

示例代码如下:

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
  struct Student
    string name;
    int age;
  ;
  
  Student students[] = { "Tom", "Jack", "Alice", 20 };
  int n = sizeof(students) / sizeof(students[0]);
  
  // 按年龄升序排序;如果年龄相同,按照添加到数组中的先后顺序排序
  std::stable_sort(students, students + n, [](const Student& s1, const Student& s2) {
    if (s1.age != s2.age)
      return s1.age < s2.age;
    
    return &s1 < &s2;
  });
  for (int i = 0; i < n; ++i) {
    cout << students[i].name << " " << students[i].age << endl;
  }
  return 0;
}

3. std::partial_sort

std::partial_sort函数可以对指定范围内的元素进行部分排序,即排名前K个或者最小(大)的k个元素。其语法如下:

std::partial_sort(first, middle, last, compare);

其中,first和last是要排序的元素区间,middle是中间位置的迭代器,指定了部分排序的范围,compare是比较函数。

示例代码如下,演示如何使用std::partial_sort函数:

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
  int arr[] = 55;
  int n = sizeof(arr) / sizeof(arr[0]);
  std::partial_sort(arr, arr + 3, arr + n, greater<int>()); // 找出前3个最大的数
  for (int i = 0; i < 3; ++i) {
    cout << arr[i] << " ";
  }
  return 0;
}

4. std::nth_element

std::nth_element函数可以在不完整地排序整个序列的情况下查找中位数、第K个最小值等。其语法如下:

std::nth_element(first, nth, last, compare);

其中,first和last是要排序的元素区间,nth是迭代器,指定了第N个元素,compare是比较函数。

示例代码如下,演示如何使用std::nth_element函数:

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
  int arr[] = 76 ;
  int n = sizeof(arr) / sizeof(arr[0]);
  std::nth_element(arr, arr + 2, arr + n, greater<int>()); // 找出第3个最大的数
  cout << arr[2] << endl;
  return 0;
}

综上所述,C++提供了多种排序函数,可以满足不同的排序需求。开发人员可以根据具体情况,选择合适的排序函数来进行优化。

  
  

评论区