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;如果两个字符串等效,则返回零。内容 |
[编辑] 参数
low1 | - | 指向第一个字符串首字符的指针 |
high1 | - | 第一个字符串的末尾后指针 |
low2 | - | 指向第二个字符串首字符的指针 |
high2 | - | 第二个字符串的末尾后指针 |
[编辑] 返回值
如果第一个字符串大于第二个字符串(即在排序顺序中位于第二个字符串之后),则返回 1;如果第一个字符串小于第二个字符串(在排序顺序中位于第二个字符串之前),则返回 -1;如果两个字符串等效,则返回零。
[编辑] 注意
当不需要三向比较时(例如,当为标准算法(如 std::sort)提供 Compare
参数时),std::locale::operator() 可能更合适。
排序顺序是字典顺序:字母在国家字母表中的位置(其等效类)比其大小写或变体具有更高的优先级。在等效类中,小写字符在它们的大写等效字符之前排序,并且特定于区域设置的顺序可能适用于带有变音符号的字符。在某些区域设置中,字符组比较为单个排序单元。例如,捷克语中的 "ch" 位于 "h" 之后,"i" 之前,而匈牙利语中的 "dzs" 位于 "dz" 之后,"g" 之前。
[编辑] 示例
运行此代码
#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
[编辑] 参见
根据当前区域设置比较两个字符串 (函数) | |
根据当前区域设置比较两个宽字符串 (函数) | |
使用此区域设置的 collate facet 按字典顺序比较两个字符串 ( std::locale 的公有成员函数) |