有没有什么方法可以使用 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/