gpt4 book ai didi

C++ 字符串像人一样排序?

转载 作者:可可西里 更新时间:2023-11-01 16:39:04 25 4
gpt4 key购买 nike

我想按照人类对它们进行排序的方式对字母数字字符串进行排序。即,“A2”出现在“A10”之前,“a”肯定出现在“Z”之前!有什么办法可以不用编写迷你解析器吗?理想情况下,它还会将“A1B1”放在“A1B10”之前。我看到问题 "Natural (human alpha-numeric) sort in Microsoft SQL 2005"有可能的答案,但它使用各种库函数,"Sorting Strings for Humans with IComparer" 也是如此。 .

下面是一个当前失败的测试用例:

#include <set>
#include <iterator>
#include <iostream>
#include <vector>
#include <cassert>

template <typename T>
struct LexicographicSort {
inline bool operator() (const T& lhs, const T& rhs) const{
std::ostringstream s1,s2;
s1 << toLower(lhs); s2 << toLower(rhs);
bool less = s1.str() < s2.str();
//Answer: bool less = doj::alphanum_less<std::string>()(s1.str(), s2.str());
std::cout<<s1.str()<<" "<<s2.str()<<" "<<less<<"\n";
return less;
}

inline std::string toLower(const std::string& str) const {
std::string newString("");
for (std::string::const_iterator charIt = str.begin();
charIt!=str.end();++charIt) {
newString.push_back(std::tolower(*charIt));
}
return newString;
}
};


int main(void) {
const std::string reference[5] = {"ab","B","c1","c2","c10"};
std::vector<std::string> referenceStrings(&(reference[0]), &(reference[5]));

//Insert in reverse order so we know they get sorted
std::set<std::string,LexicographicSort<std::string> > strings(referenceStrings.rbegin(), referenceStrings.rend());

std::cout<<"Items:\n";
std::copy(strings.begin(), strings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
std::vector<std::string> sortedStrings(strings.begin(), strings.end());
assert(sortedStrings == referenceStrings);
}

最佳答案

有什么办法可以不用编写迷你解析器吗?

让别人做?

我正在使用这个实现:http://www.davekoelle.com/alphanum.html ,我也对其进行了修改以支持 wchar_t。

关于C++ 字符串像人一样排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2783814/

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