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.
What you need to do is iterate through the string, ignoring '.' and converting the char representations of numbers into ints. Then compare the two end results.
That will give you 432 and 345, comparing those would give you which is the higher version.
Following example will demonstrates comparison between following version format:
major.minor.revision.build
or any shorter version, like onlymajor
while it allows you to extend it to fit your needs as of,Using example bellow, dots in the beginning and end of the version string are taken care of as far
.0.4
is considered to be equal to0.0.4
and.1.
is considered to be equal to0.1.0
.CompareVersion.h
CompareVersion.cpp
main.cpp
Output
Something like this would work to do the checking and is fairly minimal. It makes use of boost to split the string and then compares the version step by step. It automatically deals with missing leading zeros.
Since you know
numb[1]
would equal to '.' you can just useWhich would remove all dots in
numb1
after the second character.Here's one approach that should work for numerical version numbers:
getline(strstream, token, ".")
atoi
orstol
and compare numericallyBasically, 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
because4, "b", 7 < 4, "b", 24
).