c++ - 按 lexicographical_compare() 函数排序

标签 c++ sorting

有没有什么方法可以使用 C++ 中的 lexicographical_compare() 函数对字符串进行排序?

我可以通过 STL 排序来完成,但我的问题是关于 lexicographical_compare() 函数。

最佳答案

您不需要 std::lexicographical_compare 来对字符串进行排序。您只需要 std::sort 算法:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
  std::string s("qwertyuioplkjhgfdsazxcvbnm");
  std::cout << s << "\n";
  std::sort(s.begin(), s.end());
  std::cout << s << "\n";
}

这同样适用于对字符串集合进行排序:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main()
{
  std::vector<std::string> v{"apple" , "Apple" ,"AppLe" , "APPLe"};
  for (const auto& s : v)
    std::cout << s << " ";
  std::cout << "\n";
  std::sort(v.begin(), v.end());
  for (const auto& s : v)
    std::cout << s << " ";
  std::cout << "\n";
}

关于c++ - 按 lexicographical_compare() 函数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16463008/

相关文章:

c++ - 我该如何解决此错误 : . exe 文件已停止工作

c++ - VSPerf VS2010 和其他分析工具没有获取 pdb

c++ - 将 2 的补码转换为小数。输出是双

c++ - gcc 中的 Borland 风格 __closure

Pythonic 以棘手的顺序对字典列表进行排序

performance - 使用 CLRS 代码和 Robert Sedgewick 代码进行插入排序的运行时间差异

c++ - 带有 Placement New 的自定义析构函数

sorting - Hadoop - 按键正确排序并按 reducer 分组

Python 选择排序数据框行

javascript - 将对象转换为数组并将名称映射为键和子项