Compare versions as strings

后端 未结 4 1936
一整个雨季
一整个雨季 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 05:53

    First the test code:

    int main()
    {
        std::cout << ! ( Version("1.2")   >  Version("1.3") );
        std::cout <<   ( Version("1.2")   <  Version("1.2.3") );
        std::cout <<   ( Version("1.2")   >= Version("1") );
        std::cout << ! ( Version("1")     <= Version("0.9") );
        std::cout << ! ( Version("1.2.3") == Version("1.2.4") );
        std::cout <<   ( Version("1.2.3") == Version("1.2.3") );
    }
    // output is 111111
    

    Implementation:

    #include 
    #include 
    
    // Method to compare two version strings
    //   v1 <  v2  -> -1
    //   v1 == v2  ->  0
    //   v1 >  v2  -> +1
    int version_compare(std::string v1, std::string v2)
    {
        size_t i=0, j=0;
        while( i < v1.length() || j < v2.length() )
        {
            int acc1=0, acc2=0;
    
            while (i < v1.length() && v1[i] != '.') {  acc1 = acc1 * 10 + (v1[i] - '0');  i++;  }
            while (j < v2.length() && v2[j] != '.') {  acc2 = acc2 * 10 + (v2[j] - '0');  j++;  }
    
            if (acc1 < acc2)  return -1;
            if (acc1 > acc2)  return +1;
    
            ++i;
            ++j;
        }
        return 0;
    }
    
    struct Version
    {
        std::string version_string;
        Version( std::string v ) : version_string(v)
        { }
    };
    
    bool operator <  (Version u, Version v) {  return version_compare(u.version_string, v.version_string) == -1;  }
    bool operator >  (Version u, Version v) {  return version_compare(u.version_string, v.version_string) == +1;  }
    bool operator <= (Version u, Version v) {  return version_compare(u.version_string, v.version_string) != +1;  }
    bool operator >= (Version u, Version v) {  return version_compare(u.version_string, v.version_string) != -1;  }
    bool operator == (Version u, Version v) {  return version_compare(u.version_string, v.version_string) ==  0;  }
    

    https://coliru.stacked-crooked.com/a/7c74ad2cc4dca888

提交回复
热议问题