SuperMurloc SuperMurloc - 1 month ago 12
C++ Question

Fast way to do lexicographical comparing 2 numbers

I'm trying to sort a vector of unsigned int in lexicographical order.

The std::lexicographical_compare function only supports iterators so I'm not sure how to compare two numbers.

This is the code I'm trying to use:

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());
} );

Answer

C++11 introduces std::to_string

You can use from to_string as below:

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());
} );
Comments