1. 关键词 关键词:
C++ 版本号处理 版本号比较 跨平台
实现原理:
通过字符串分割,对每一段的版本号进行逐一比较。
应用场景:
要基于版本号做一些逻辑区分时,比如:要大于某个特定的版本才支持某个功能。
2. verutil.h 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #pragma once #include <string> namespace cutl{ int compare_version (const std::string &v1, const std::string &v2) ; }
3. verutil.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 #include <regex> #include "verutil.h" #include "strutil.h" #include "inner/logger.h" namespace cutl{ int compare_version (const std::string &v1, const std::string &v2) { auto arr1 = split (v1, "." ); auto arr2 = split (v2, "." ); int len1 = arr1.size (); int len2 = arr2.size (); int len = std::max (len1, len2); for (int i = 0 ; i < len; i++) { int num1 = i < len1 ? std::stoi (arr1[i]) : 0 ; int num2 = i < len2 ? std::stoi (arr2[i]) : 0 ; if (num1 < num2) { return -1 ; } else if (num1 > num2) { return 1 ; } } return 0 ; } }
4. 测试代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #include "common.hpp" #include "verutil.h" void TestCompareVersion () { PrintSubTitle ("TestCompareVersion" ); auto version1 = "3.28.3" ; auto version2 = "3.2.2" ; auto version3 = "3.30.0" ; auto adjective = [](int ret) { return ret > 0 ? " greater than " : (ret < 0 ? " less than " : " equal to " ); }; auto ret1 = cutl::compare_version (version1, version2); std::cout << version1 << adjective (ret1) << version2 << std::endl; auto ret2 = cutl::compare_version (version1, version3); std::cout << version1 << adjective (ret2) << version3 << std::endl; }
5. 运行结果 1 2 3 -----------------------------------------TestCompareVersion----------------------------------------- 3.28.3 greater than 3.2.2 3.28.3 less than 3.30.0
6. 源码地址 更多详细代码,请查看本人写的C++ 通用工具库: common_util , 本项目已开源,代码简洁,且有详细的文档和Demo。