Sorting an array of version numbers in C ++

Given an array of version numbers, such as:

vector<string> v = { "9.8.17.5295", "9.13.0.0",
                          "12.3.9.1017", "25.3.6.1" };

What is the best way to sort them in C ++? The problem here, of course, is that we cannot just sort them lexicographically, but we must divide each line into components and compare these components numerically. In Python, this can be done as follows:

v.sort(key=lambda x : tuple(map( int, x.split('.'))))

But how to do it in C ++? Everything I can think of seems rather cumbersome compared to this one-liner. The best I have found so far is:

array<int, 4> splitversion( const string& s )
{
    array<int, 4> z;
    sscanf( s.c_str(), "%d.%d.%d.%d", &z[0], &z[1], &z[2], &z[3] );
    return z;
}

int main()
{
    vector<string> v = { "9.8.17.5295", "25.3.6.1", "9.13.0.0", "12.3.9.1017" };
    sort( v.begin(), v.end(), []( string s1, string s2 )
          { return splitversion( s1 ) < splitversion(  s2 ); } );
}

Of course, sscanf frowns with C ++ people, so I may have to replace it with something else, but as far as I can tell, this is becoming even more cumbersome. How do you do this?

+4
2

:) . . :

array<int, 4> z;
sscanf( s.c_str(), "%d.%d.%d.%d", &z[0], &z[1], &z[2], &z[3] );
unsigned long long hash = (z[0] << 24) +  (z[1] << 16) +  (z[2] << 8) + z[3];

/, . . , . -, .

+1

,

char c;
istringstream(s) >> z[0] >> c >> z[1] >> c >> z[2] >> c >> z[3];

, - boost::spirit, , , vector<pair<array<int, 4>, string>> .

0

All Articles