There are two values:
QString str1 = "3.5.8", str2 = "20.3.6";
Let's imagine that these two numbers
represent the software version
, as it were.
It is known that QString
compares character-by-character.
What if we approach this decision in this way:
str1.replace(".","");
str2.replace(".","");
int n = str1.toInt();
int m = str2.toInt();
if (n >= m)
{
qDebug() << "YES";
} else if (n <= m) {
qDebug() << "NO";
}
Maybe there is a more optimal and correct way to do this.
Could you tell me please how I can translate these values into numbers so that they can be compared in their entirety. Thanks.
CodePudding user response:
The QVersionNumber
class was designed to solve this problem (requires Qt 5.6 ):
QVersionNumber version1 = QVersionNumber::fromString(str1);
QVersionNumber version2 = QVersionNumber::fromString(str2);
if (version1 > version2)
{
qDebug() << "YES";
}
else
{
qDebug() << "NO";
}
CodePudding user response:
Quite frankly I'd first parse them to real ints, and then convert those; something like this:
const std::string s1 = str1.toStdString();
const std::string s2 = str2.toStdString();
struct { int major, minor, tag; } v0, v1;
int r1=sscanf(s1.c_str(),"%i.%i.%i",&v0.major,&v0.minor,&v0.tag);
...
Then you can compare versions on major/minor/etc as you require. Of course you do want to add some error-checking on the result of sscanf, and possibly look into sscanf_s for safety concerns.
CodePudding user response:
Use split
method to have QStringList
s, use std::transform
to convert them to vector<int>
, finally use lexicographical_compare
.
Suboptimal performance-wise, verbose, but correct and idiomatic.