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

相关推荐
玖玥拾3 小时前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you4 小时前
constexpr函数
c++
凡人叶枫5 小时前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫5 小时前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss5 小时前
BRpc使用
c++·rpc
-森屿安年-5 小时前
63. 不同路径 II
c++·算法·动态规划
chase_my_dream6 小时前
Cartographer详细讲解
c++·人工智能·自动驾驶
森G6 小时前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt
碧海蓝天20226 小时前
C++法则24:在标准 C++ 中,没有任何可移植的方式判断指针 T* pt 指向的内存位置是否已经 构造了对象,程序员必须手动跟踪哪些元素已构造。
java·开发语言·c++
charlie1145141916 小时前
现代C++指南:Lambda,让我们用另一种方式持有函数
开发语言·c++