21xrx.com
2024-09-19 09:35:48 Thursday
登录
文章检索 我的文章 写文章
C++字符串字典排序
2023-07-03 15:22:31 深夜i     --     --
C++ 字符串 字典排序 排序算法 STL库函数

字典排序是一种常见的排序方法,在计算机科学中获得了广泛应用。而在C++中,我们可以使用字符串来进行字典排序。本篇文章将通过以下步骤介绍C++字符串字典排序的实现方法。

首先,我们需要定义一个字符串数组,并在其中存储需要进行排序的字符串。接着,我们可以使用C++的STL库中的sort函数来对这个字符串数组进行排序:


#include <iostream>

#include <algorithm>

#include <string>

using namespace std;

int main() {

  string str[] = "apple";

  sort(str, str+5);

  for(int i = 0; i < 5; i++) {

    cout << str[i] << " ";

  }

  cout << endl;

  return 0;

}

以上代码就是一个简单的字符串字典排序实现,输出结果为:


apple cat dog hello world

其实sort函数默认就是按照字典顺序来排序字符串的,所以不需要额外的比较函数。

如果需要降序排列,可以使用greater函数:


sort(str, str+5, greater<string>());

以上代码将字符串数组按照字典顺序倒序排序。

当然,以上代码只是简单地对字符串数组进行了排序,如果需要对字符串的某一个部分进行排序,可以定义一个排序函数并传入sort函数。例如:


#include <iostream>

#include <algorithm>

#include <string>

using namespace std;

bool compare(string a, string b) {

  return a.substr(1) < b.substr(1);

}

int main() {

  string str[] = "dog";

  sort(str, str+5, compare);

  for(int i = 0; i < 5; i++) {

    cout << str[i] << " ";

  }

  cout << endl;

  return 0;

}

以上代码将字符串数组按照第二个字符进行了排序,输出结果为:


world dog apple hello cat

以上就是C++字符串字典排序的简单实现,通过定义字符串数组和排序函数,就可以方便地对字符串进行字典排序了。

  
  

评论区

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