gpt4 book ai didi

c++ - 将版本作为字符串进行比较

转载 作者:可可西里 更新时间:2023-11-01 18:42:01 24 4
gpt4 key购买 nike

将版本号作为字符串进行比较并不那么容易...
“1.0.0.9” > “1.0.0.10”,但不正确。
正确执行此操作的明显方法是解析这些字符串,转换为数字并作为数字进行比较。还有另一种方法可以更“优雅”地做到这一点吗?例如,boost::string_algo...

最佳答案

我看不出有什么比解析更优雅的了——但是使用已经存在的标准库设施。假设您不需要错误检查:

void Parse(int result[4], const std::string& input)
{
std::istringstream parser(input);
parser >> result[0];
for(int idx = 1; idx < 4; idx++)
{
parser.get(); //Skip period
parser >> result[idx];
}
}

bool LessThanVersion(const std::string& a,const std::string& b)
{
int parsedA[4], parsedB[4];
Parse(parsedA, a);
Parse(parsedB, b);
return std::lexicographical_compare(parsedA, parsedA + 4, parsedB, parsedB + 4);
}

任何更复杂的东西都将更难维护,不值得你花时间。

关于c++ - 将版本作为字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2941491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com