std::collate<CharT>:: compare, std::collate<CharT>:: do_compare
|
定义于头文件
<locale>
|
||
|
public
:
int
compare
(
const
CharT
*
low1,
const
CharT
*
high1,
|
(1) | |
|
protected
:
virtual
int
do_compare
(
const
CharT
*
low1,
const
CharT
*
high1,
|
(2) | |
do_compare
。
[
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
参见
|
根据当前本地化设置比较两个字符串
(函数) |
|
|
根据当前本地化设置比较两个宽字符串
(函数) |
|
|
使用此本地环境的排序刻面按字典序比较两个字符串
(
std::locale
的公开成员函数)
|