gpt4 book ai didi

c++ - 首先按字母顺序然后按数字对数字列表进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 13:48:25 77 4
gpt4 key购买 nike

我需要先按字母顺序对给定数字进行排序,然后再按数字升序对给定数字进行排序。例如我有这些数字

{"10", "1", "2", "20", "200", "3", "300", "30", "201", "21"}

我要这个订单

{"1", "10", "2", "20", "21", "200", "201", "3", "30", "300"}

我写了下面的比较函数来对它们进行排序。

bool AlphaNumericCompare(const string & str1, const string& str2 )
{
int ind1 = 0, ind2 = 0;
while ( ind1 < str1.size() && ind2 < str2.size() )
{
if( str1[ind1] < str2[ind2] )
return true;
else if( str1[ind1] > str2[ind2] )
return false;
ind1++;
ind2++;
}
if( ind1 == str1.size() && ind2 == str2.size() )
{
return true;
}
else if( ind1 == str1.size() )
{
return true;
}
return false;
}

但是这个函数给了我以下顺序

{"1", "10", "2", "20",  "200", "201", "21", "3", "30", "300"}

其中 200 和 201 位于 21 之前。谁能建议如何更改上述比较函数以获得所需的排序顺序?

最佳答案

一个电话std::sort应该足够了,具有自定义比较器功能。有点像

std::sort(std::begin(collection), std::end(collection),
[](const std::string& s1, const std::string& s2)
{
auto i1 = std::stoll(s1);
auto i2 = std::stoll(s2);
return (s1 < s2 && i1 < i2);
});

请注意,它未经测试。

关于c++ - 首先按字母顺序然后按数字对数字列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24673511/

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