21xrx.com
2024-09-20 00:37:19 Friday
登录
文章检索 我的文章 写文章
C++ 字符串排序
2023-06-27 05:09:06 深夜i     --     --
C++ 字符串 排序

C++ 是一种高级编程语言,它具有广泛的应用范围。其中字符串排序是一个非常基础的问题,但也是必要的。本文将介绍 C++ 字符串排序的方法。

首先,C++ 中的字符串可以通过使用 string 类型实现。该类型具有成员函数 sort(),可以对字符串进行排序。例如,下面的代码演示了如何对字符串 s 进行排序:


#include <iostream>

#include <algorithm>

#include <string>

using namespace std;

int main()

{

  string s = "hello world";

  sort(s.begin(), s.end());

  cout << s << endl;

  return 0;

}

输出结果如下:


dehllloorw

可以看到,字符串中的所有字符已经按照字典序排列。

除了使用 string 类型外,还可以使用 char 数组实现字符串排序。这里我们可以使用标准库中的 qsort() 函数。该函数需要传递一个数组指针,以及一个比较函数指针,用于定义排序规则。下面的代码演示了使用 qsort() 函数对字符串数组进行快速排序的方法:


#include <iostream>

#include <cstring>

#include <cstdlib>

using namespace std;

int cmp(const void* a, const void* b)

{

  const char** pa = (const char**) a;

  const char** pb = (const char**) b;

  return strcmp(*pa, *pb);

}

int main()

{

  const int N = 5;

  const char* s[N] = {"hello", "world", "apple", "banana", "cat"};

  qsort(s, N, sizeof(char*), cmp);

  for (int i = 0; i < N; i++)

  {

    cout << s[i] << endl;

  }

  return 0;

}

输出结果如下:


apple

banana

cat

hello

world

以上就是两种不同的方法实现 C++ 字符串的排序。无论采用哪种方法,在实际使用中要根据具体情况进行选择。为了保证代码的可维护性和可读性,可以在代码中添加足够的注释和说明。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复