C++版本号处理3 - 版本号比较

1. 关键词

关键词:

C++ 版本号处理 版本号比较 跨平台

实现原理:

通过字符串分割,对每一段的版本号进行逐一比较。

应用场景:

要基于版本号做一些逻辑区分时,比如:要大于某个特定的版本才支持某个功能。

2. verutil.h

#pragma once

#include <string>

namespace cutl
{
    /**
     * @brief Compare two version strings.
     *
     * @param v1 version string 1.
     * @param v2 version string 2.
     * @return int The result of the comparison. -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2.
     */
    int compare_version(const std::string &v1, const std::string &v2);
} // namespace cutl

3. verutil.cpp

#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;
    }
} // namespace cutl

4. 测试代码

#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. 运行结果

-----------------------------------------TestCompareVersion-----------------------------------------
3.28.3 greater than 3.2.2
3.28.3 less than 3.30.0

6. 源码地址

更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。

posted @ 2024-06-27 22:12  陌尘(MoChen)  阅读(2)  评论(0编辑  收藏  举报