21xrx.com
2025-03-25 05:03:31 Tuesday
文章检索 我的文章 写文章
C++字符串排序
2023-06-24 02:15:23 深夜i     22     0
C++ 字符串 排序

在C++中,字符串排序是一个非常常见的操作。对于一个字符串数组,我们可以使用sort算法来对其进行排序。

sort算法默认按字符的ASCII码值进行排序。如果想要字符串按照字符串的实际大小进行排序,可以使用自定义的比较函数。

下面是一段使用比较函数对字符串数组进行排序的示例代码:

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
bool cmp(string a, string b)
  return a < b;
int main() {
  string arr[] = "the";
  int n = sizeof(arr)/sizeof(arr[0]);
  sort(arr, arr + n, cmp);
  // 打印排序后的字符串数组
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  return 0;
}

在该代码中,我们首先定义了一个自定义的比较函数cmp,其会对两个字符串进行比较,并返回一个bool值,表示哪一个字符串更小。

然后,我们定义了一个字符串数组arr,并使用sort算法对其进行排序,排序方式使用我们之前定义的比较函数cmp。

最后,我们使用for循环打印排序后的字符串数组。

这样,就可以方便地对字符串数组进行排序了。如果需要按照其他排序方式进行排序,只需要修改比较函数即可。

  
  

评论区

请求出错了