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 发布!

相关推荐
mjhcsp2 分钟前
C++ int 类型深度解析:从底层实现到实战应用
c++·int
程序员老舅1 小时前
C++参数传递:值、指针与引用的原理与实战
c++·c/c++·值传递·引用传递·指针传递·参数传递机制
liu****2 小时前
8.list的使用
数据结构·c++·算法·list
立志成为大牛的小牛2 小时前
数据结构——二十六、邻接表(王道408)
开发语言·数据结构·c++·学习·程序人生
草莓熊Lotso3 小时前
C++ 方向 Web 自动化测试入门指南:从概念到 Selenium 实战
前端·c++·python·selenium
CoderCodingNo4 小时前
【GESP】C++五级考试大纲知识点梳理, (5) 算法复杂度估算(多项式、对数)
开发语言·c++·算法
星河队长4 小时前
VS创建C++动态库和C#访问过程
java·c++·c#
沐怡旸5 小时前
【穿越Effective C++】条款02:尽量以const, enum, inline替换#define
c++·面试
给大佬递杯卡布奇诺6 小时前
FFmpeg 基本API avcodec_alloc_context3函数内部调用流程分析
c++·ffmpeg·音视频
QT 小鲜肉6 小时前
【个人成长笔记】Qt 中 SkipEmptyParts 编译错误解决方案及版本兼容性指南
数据库·c++·笔记·qt·学习·学习方法