c++ 自然排序-window檔案排序
阿新 • • 發佈:2021-11-09
轉載:(10條訊息) C++字串操作之字串自然排序_zhanghm1995的部落格-CSDN部落格
//自然排序 bool compareNat(const std::string &a, const std::string &b) { if (a.empty()) return true; if (b.empty()) return false; if (std::isdigit(a[0]) && !std::isdigit(b[0])) return true; if (!std::isdigit(a[0]) && std::isdigit(b[0])) return false; if (!std::isdigit(a[0]) && !std::isdigit(b[0])) { if (std::toupper(a[0]) == std::toupper(b[0])) return compareNat(a.substr(1), b.substr(1)); return (std::toupper(a[0]) < std::toupper(b[0])); } // Both strings begin with digit --> parse both numbers std::istringstream issa(a); std::istringstream issb(b);int ia, ib; issa >> ia; issb >> ib; if (ia != ib) return ia < ib; // Numbers are the same --> remove numbers and recurse std::string anew, bnew; std::getline(issa, anew); std::getline(issb, bnew); return (compareNat(anew, bnew)); } bool judge(const pair<string, string> a, const pair<string, string> b) { return compareNat(a.first, b.first); }