如何比较C ++中的版本号 [英] How to compare version numbers in C++

查看:362
本文介绍了如何比较C ++中的版本号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的教授希望我们编写一个程序来比较两个版本号,如0.1 < 0.2或1 < 1.1。也有一些招trick如.0.4< .1。
所以,我的想法是首先判断如果数字开始为点,如果它,我添加一个0。之后,我删除除第一个之外的其他点。然后我将字符串转换为数字并进行比较。这是我在第一步做的。

  string numb1,numb2; 
if(numb1 [0] =='。')
{
numb1 =0+ numb1;
}

我对第二个数字做同样的事情。现在我需要帮助,告诉我如何删除除了第一个点之外的点。
我们的教授希望我们使用这个特定的函数:
int compareVersions(string ver1,string ver2)。
如果ver1> ver2:return 1
如果ver1< ver2:return -1
否则返回0.



顺便说一下,一些视觉编号可能很长,如2.3.2.2.3.1.1.5.3.5 .6.2或1.1.1.1.1.1.1。

解决方案

这里有一种方法适用于数字版本号:




  • 使用 getline(strstream,token,。)将输入字符串拆分成 / li>
  • 使用 atoi stol 将相应的数字转换为数字, li>


基本上,将版本号视为由分隔的数字序列,请注意,一个实用的通用版本号比较算法可能需要处理额外的棘手性,例如字母后缀(字母后缀例如 1.1e 2.4b24 3.5rc1 我假设这是一个类练习的范围之外,但方法是类似的:将这些部分分成数字和非数字部分的序列,并比较每个部分(例如 2.4b7< 2.4b24 ,因为 4,b,7 < 4,b,24 )。


Our professor want us to write a program to compare two version numbers, like 0.1 < 0.2 or 1 < 1.1. Also there are some trick ones like .0.4 < .1. So, my idea is first judge if the number start as a dot, if it does, I add a 0 to it. After that I remove other dots except the first one. Then I convert string to number and compare them. Here's what I do in the first step.

string numb1,numb2;
if(numb1[0]=='.')
{
    numb1 ="0"+ numb1;
}

I do the same thing to the second number. And now I need help to show me how to remove the dots except the first one. Our professor want us to use this specific function: int compareVersions(string ver1, string ver2). If ver1 > ver2: return 1 if ver1 < ver2: return -1 otherwise return 0.

By the way, some of the vision number may very long like 2.3.2.2.3.1.1.5.3.5.6.2 or 1.1.1.1.1.1.1.

解决方案

Here's one approach that should work for numerical version numbers:

  • Split the input strings into pieces using getline(strstream, token, ".")
  • Convert corresponding pieces to numbers using atoi or stol and compare numerically

Basically, treat the version numbers as sequences of numbers separated by . and compare those sequences lexicographically.


Note that a practical, general version number comparison algorithm probably needs to handle extra trickiness such as letter suffixes (e.g. 1.1e, 2.4b24, 3.5rc1), etc. I'm assuming that this is outside the scope of a class exercise, but the approach is similar: split these parts into sequences of numeric and non-numeric parts and compare each part (e.g. 2.4b7 < 2.4b24 because 4, "b", 7 < 4, "b", 24).

这篇关于如何比较C ++中的版本号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆