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

  • [1. 关键词](#1. 关键词)
  • [2. verutil.h](#2. verutil.h)
  • [3. verutil.cpp](#3. verutil.cpp)
  • [4. 测试代码](#4. 测试代码)
  • [5. 运行结果](#5. 运行结果)
  • [6. 源码地址](#6. 源码地址)

1. 关键词

关键词:

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

实现原理:

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

应用场景:

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

2. verutil.h

c++ 复制代码
#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

c++ 复制代码
#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. 测试代码

c++ 复制代码
#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. 运行结果

bash 复制代码
-----------------------------------------TestCompareVersion-----------------------------------------
3.28.3 greater than 3.2.2
3.28.3 less than 3.30.0

6. 源码地址

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

本文由博客一文多发平台 OpenWrite 发布!

相关推荐
一木 之林4 分钟前
五、C++ 新特性、关键字与编译原理(进阶)(一)
c语言·开发语言·c++
2601_962298275 分钟前
交易开拓者通常使用什么编程语言?这种语言如何帮助自动化交易?
java·c++·python·编程语言·自动化交易
码匠许师傅11 分钟前
【设计模式精讲】23.备忘录模式(Memento)
c++·设计模式·软件工程·uml·备忘录模式
键盘会跳舞34 分钟前
【C++多线程】thread_local 深度剖析:线程局部存储的生命周期与实现
c++·多线程·thread_local
whitelbwwww35 分钟前
c++ 多线程
开发语言·c++·算法
努力努力再努力wz44 分钟前
【Docker入门系列】:从架构演进到容器化:一文建立 Docker、虚拟化与 Namespace 的底层心智模型
运维·开发语言·数据结构·c++·docker·容器·架构
光电笑映1 小时前
Linux 线程编程:从进程、分页到线程控制与封装
linux·运维·服务器·c++
qinzechen1 小时前
本周科技行业热点汇总·2026第36周(2026年8月31日-9月6日)
c++·科技·算法
aqiu1111111 小时前
【C++ 代码分析与重构】常见 DFS 逻辑错误解析与修正
c++·重构·深度优先
zuozong_1 小时前
C++类与对象
开发语言·c++·算法