对 wstring
vector 进行排序时:
vector<wstring> v;
v.push_back(L"zzz");
v.push_back(L"BBB");
v.push_back(L"aaa");
sort(v.begin(), v.end());
结果是 BBB、aaa、zzz。 如何进行不区分大小写的排序?
我尝试过
sort(v.begin(), v.end(),
[](wstring lhs, wstring rhs) { return tolower(lhs) < tolower(rhs); });
但没有任何成功,因为 tolower
仅适用于 char/wchar_t,而不适用于 wstring。
我可能必须使用lexicographical_compare
但我不明白怎么办。
(因为我正在寻找一种有效的排序方法,能够在短时间内对数百万个 wstring 进行排序,所以我认为临时存储所有 wstring 小写的拷贝,并对第二个 vector 进行排序并不是一个好的选择想法?)
最佳答案
but without any success because tolower works only char / wchar_t.
你想要 std::ctype<wchar_t>::tolower
:
auto& f = use_facet<ctype<wchar_t>>(locale());
sort(v.begin(), v.end(), [&f](wstring const& a, wstring const& b) {
return lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), [&f](wchar_t ai, wchar_t bi) {
return f.tolower(ai) < f.tolower(bi);
});
});
或者,代替 std::ctype<wchar_t>::tolower
您可能喜欢使用 towlower
使用当前(全局)C
语言环境。
关于c++ - 对 wstrings vector 进行排序,但不区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45490542/