std::collate<CharT>::compare, std::collate<CharT>::do_compare
来自 cppreference.cn
定义于头文件 <locale> |
||
public: int compare( const CharT* low1, const CharT* high1, |
(1) | |
protected: virtual int do_compare( const CharT* low1, const CharT* high1, |
(2) | |
1) 公有成员函数,调用派生程度最高的类中的保护虚成员函数
do_compare
。2) 使用此区域设置的排序规则,比较字符序列
[
low1,
high1)
与字符序列 [
low2,
high2)
,如果第一个字符串在第二个字符串之后,则返回 1,如果第一个字符串在第二个字符串之前,则返回 -1,如果两个字符串等价,则返回零。目录 |
[edit] 参数
low1 | - | 指向第一个字符串的第一个字符的指针 |
high1 | - | 第一个字符串的结束指针之后一位 |
low2 | - | 指向第二个字符串的第一个字符的指针 |
high2 | - | 第二个字符串的结束指针之后一位 |
[edit] 返回值
如果第一个字符串大于第二个字符串(即在排序顺序中位于第二个字符串之后),则返回 1,如果第一个字符串小于第二个字符串(在排序顺序中位于第二个字符串之前),则返回 -1,如果两个字符串等价,则返回零。
[edit] 注意
当不需要三路比较时(例如,在为标准算法(如 std::sort)提供 Compare
参数时),std::locale::operator() 可能更合适。
排序顺序是字典顺序:字母在国家字母表中的位置(其等价类)具有比其大小写或变体更高的优先级。在等价类中,小写字符在它们的大写对应物之前排序,并且特定于区域设置的顺序可能适用于带变音符号的字符。在某些区域设置中,字符组作为单个排序单元进行比较。例如,捷克语中的 "ch" 在 "h" 之后,在 "i" 之前;匈牙利语中的 "dzs" 在 "dz" 之后,在 "g" 之前。
[edit] 示例
运行此代码
#include <iostream> #include <locale> #include <string> template<typename CharT> void try_compare(const std::locale& l, const CharT* p1, const CharT* p2) { auto& f = std::use_facet<std::collate<CharT>>(l); std::basic_string<CharT> s1(p1), s2(p2); if (f.compare(&s1[0], &s1[0] + s1.size(), &s2[0], &s2[0] + s2.size()) < 0) std::wcout << p1 << " before " << p2 << '\n'; else std::wcout << p2 << " before " << p1 << '\n'; } int main() { std::locale::global(std::locale("en_US.utf8")); std::wcout.imbue(std::locale()); std::wcout << "In the American locale: "; try_compare(std::locale(), "hrnec", "chrt"); std::wcout << "In the Czech locale: "; try_compare(std::locale("cs_CZ.utf8"), "hrnec", "chrt"); std::wcout << "In the American locale: "; try_compare(std::locale(), L"år", L"ängel"); std::wcout << "In the Swedish locale: "; try_compare(std::locale("sv_SE.utf8"), L"år", L"ängel"); }
输出
In the American locale: chrt before hrnec In the Czech locale: hrnec before chrt In the American locale: ängel before år In the Swedish locale: år before ängel
[edit] 参阅
根据当前区域设置比较两个字符串 (函数) | |
根据当前语言环境比较两个宽字符串 (函数) | |
使用此区域设置的 collate facet 对两个字符串进行字典比较 ( std::locale 的公有成员函数) |