Compare versions as strings

后端 未结 4 1939
一整个雨季
一整个雨季 2020-12-16 05:20

Comparing version numbers as strings is not so easy...
\"1.0.0.9\" > \"1.0.0.10\", but it\'s not correct.
The obvious way to do it properly is to parse these strings

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 06:06

    I don't see what could be more elegant than just parsing -- but please make use of standard library facilities already in place. Assuming you don't need error checking:

    void Parse(int result[4], const std::string& input)
    {
        std::istringstream parser(input);
        parser >> result[0];
        for(int idx = 1; idx < 4; idx++)
        {
            parser.get(); //Skip period
            parser >> result[idx];
        }
    }
    
    bool LessThanVersion(const std::string& a,const std::string& b)
    {
        int parsedA[4], parsedB[4];
        Parse(parsedA, a);
        Parse(parsedB, b);
        return std::lexicographical_compare(parsedA, parsedA + 4, parsedB, parsedB + 4);
    }
    

    Anything more complicated is going to be harder to maintain and isn't worth your time.

提交回复
热议问题