c++ - Sorting strings by characters first -


i using std::map in c++ , it's sorting keys in alphabetical way, this:

aaa, aa0, aa1, aab, ac1 = aa0->aa1->aaa->aab->ac1

but sort in different way:

aaa, aa0, aa1, aab, ac1 = aaa->aab->aa0->aa1->ac1

how write comparing class std::map, solve problem? don't know how that. here's definition of comparing class:

struct comp {     bool operator()(const std::string& lhs, const std::string& rhs) const     {        //dont know should write here     }; }; 

if understand correctly, want digits sort after alphabetical characters. anytime can resume sorting criteria down ordering of letters, can use std::lexicographical_compare, passing comparison operator need on characters.

i combine in single comparision operator:

struct comp {     bool isdigit( char lhs ) const     {         return ::isdigit( static_cast<unsigned char>( lhs ) );     }      bool operator()( char lhs, char rhs ) const     {         return isdigit( lhs ) == isdigit( rhs )             ? lhs < rhs             : isdigit( rhs );     }      bool operator()( std::string const& lhs, std::string const& rhs ) const     {         return std::lexicographical_compare(             lhs.begin(), lhs.end(), rhs.begin(), rhs.end(), *this);     } }; 

for more generalized comparisons, can provide map of values compare, , use it:

bool comp::operator()( char lhs, char rhs ) const {     return mymap[ static_cast<unsigned char>( lhs ) ]         <  mymap[ static_cast<unsigned char>( rhs ) ]; } 

this allow imaginable ordering, long ordering can done character character.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -