나는 인간이 그들을 분류하는 방식으로 영숫자 문자열을 정렬하고 싶습니다. 즉, "A2"는 "A10"앞에오고 "a"는 확실히 "Z"앞에옵니다! 미니 파서를 작성하지 않고 할 수있는 방법이 있습니까? 이상적으로 "A1B1"앞에 "A1B1"을 넣을 수도 있습니다. 가능한 답변으로 "Natural (human alpha-numeric) sort in Microsoft SQL 2005"이라는 질문이 표시되지만 "Sorting Strings for Humans with IComparer"처럼 다양한 라이브러리 기능을 사용합니다.C++ 문자열은 인간과 비슷합니까?
#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);
}
'집합'을 사용하는 이유가 '벡터'뿐만 아니라 '정렬'이 아닌가? –
첫째, A1B2가 A2B1에 비해 어떻게 정렬됩니까? 나는 이것을 해본 적이 없지만, 아마도 당신의 끈을 덩어리로 깨기 시작할 것입니다. 텍스트, 숫자, 텍스트, 숫자 등. 그런 다음 숫자 비트가 문자열이 아닌 숫자로 정렬된다는 이해와 함께 여러 멤버가있는 다른 데이터 구조와 동일한 방식으로 정렬합니다. –
@ 형제 : 특별한 이유가 없습니다. @Zickefoose : 나는 A1B2, A1B10, A2B1과 같이 (오름차순) 정렬 할 것입니다. 나는 당신이 원시적 인 렉싱 (lexing)을해야만 할 수도 있다고 생각하지만, 도움이된다면 오류가 발생하기 쉬운 것을 피하려고한다. –