c++ - 按字典顺序比较 2 个数字的快速方法

标签 c++ c++14 lexicographic

我正在尝试按字典顺序对 unsigned int vector 进行排序。

std::lexicographyal_compare 函数仅支持迭代器,因此我不确定如何比较两个数字。

这是我尝试使用的代码:

std::sort(myVector->begin(),myVector->end(), [](const unsigned int& x, const unsigned int& y){
        std::vector<unsigned int> tmp1(x);
        std::vector<unsigned int> tmp2(y);
        return lexicographical_compare(tmp1.begin(),tmp1.end(),tmp2.begin(),tmp2.end());
} );

最佳答案

C++11 引入 std::to_string

您可以使用 from to_string 如下:

std::sort(myVector->begin(),myVector->end(), [](const unsigned int& x, const unsigned int& y){
        std::string tmp1 = std::to_string(x);
        std::string tmp2 = std::to_string(y);
        return lexicographical_compare(tmp1.begin(),tmp1.end(),tmp2.begin(),tmp2.end());
} );

关于c++ - 按字典顺序比较 2 个数字的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40232471/

相关文章:

c - C 语言的字典顺序

algorithm - 如何将数字编码为字符串,使生成的字符串的字典顺序与数字顺序相同

c++ - 使用Eigen::FFT执行FFT时的频率

c++ - 使用的C++程序堆栈大小何时确定?

c++ - 如何在 C/C++ 中关闭特定客户端的套接字?

c++ - 如何编写丢弃其参数的通用可变参数 lambda?

c++ - std::transform 自定义树为新树

c++ - OpenGL:当尺寸不能被 4 整除时,灰度纹理数据布局不匹配

c++ - 为什么 C++ 设计者选择不允许非成员运算符 ()()?

java - 获取下一个字典字符