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

相关推荐
R-G-B4 小时前
【08】C++实战篇——C++ 生成动态库.dll 及 C++调用DLL,及实际项目中的使用技巧
c++·c++ 生成动态库.dll·c++ 生成静态库.lib·c++调用动态库.dll·c++调用静态库.lib·c++调用dll·c++调用lib
朝朝又沐沐5 小时前
算法竞赛阶段二-数据结构(40)数据结构栈的STL
开发语言·数据结构·c++·算法
Antonio9156 小时前
【网络编程】WebSocket 实现简易Web多人聊天室
前端·网络·c++·websocket
清朝牢弟7 小时前
Ubuntu系统VScode实现opencv(c++)图像放缩与插值
c++·vscode·opencv·ubuntu·计算机视觉
呆瑜nuage7 小时前
list的使用和模拟
c++·list
tomato098 小时前
Codeforces Round 1040 (Div. 2)(补题)
c++
好好先森&8 小时前
C语言:模块化编程
c语言·c++·windows
爱学习的小邓同学9 小时前
c++ --- priority_queue的使用以及简单实现
c++
清朝牢弟10 小时前
Ubuntu系统VScode实现opencv(c++)视频的处理与保存
c++·人工智能·vscode·opencv·ubuntu