c++如何实现字符串排序

2023-04-07 06:17:00 字符串 排序 如何实现

C++如何实现字符串排序

在C++中实现字符串排序有多种方法。

一种方法是使用STL中的算法,如sort,它可以对任意类型的数据进行排序。只需要提供一个比较函数来指定字符串的排序规则。

例如,如果要按字典序排序字符串,可以使用以下代码:

#include #include #include using namespace std; bool CompareString(const string &s1, const string &s2) { return s1 < s2; } int main() { vector str_vec; // 待排序字符串数组 sort(str_vec.begin(), str_vec.end(), CompareString); return 0; }

另一种方法是使用自己实现的排序算法,如冒泡排序,快速排序等。

下面是一个使用冒泡排序算法对字符串按字典序排序的例子:

#include #include using namespace std; void BubbleSort(vector &str_vec) { for (int i = 0; i < str_vec.size(); ++i) { for (int j = i + 1; j < str_vec.size(); ++j) { if (str_vec[i] > str_vec[j]) { swap(str_vec[i], str_vec[j]); } } } } int main() { vector str_vec; // 待排序字符串数组 BubbleSort(str_vec); return 0; }

相关文章