std::locale::operator()

来自cppreference.com
< cpp‎ | locale‎ | locale
template< class CharT, class Traits, class Alloc >

bool operator()( const basic_string<CharT,Traits,Alloc>& s1,

                 const basic_string<CharT,Traits,Alloc>& s2) const;

按照此 locale 的 std::collate<charT> 平面所定义的比较规则,比较二个 string 参数 s1s2 。此运算符允许以任何拥有 collate 平面的 locale 对象为标准算法(如 std::sort )和有序容器( std::set )中的二元谓词。

参数

s1 - 要比较的第一字符串
s2 - 要比较的第二字符串

返回值

s1 按字典序小于 s2 则为 true ,否则为 false

可能的实现

template<class CharT, class Traits, class Alloc >
bool operator()(const std::basic_string<CharT,Traits,Alloc>& s1,
                const std::basic_string<CharT,Traits,Alloc>& s2) const;
{
    return std::use_facet<std::collate<CharT>>(*this).compare(
                                         s1.data(), s1.data() + s1.size(),
                                         s2.data(), s2.data() + s2.size()   ) < 0;
}

示例

string 的 vector 能以 locale 对象为比较器,按照非默认的本地环境排序:

#include <locale>
#include <algorithm>
#include <vector>
#include <string>
#include <cassert>
 
int main()
{
    std::vector<std::wstring> v = {L"жил", L"был", L"кот"};
    std::sort(v.begin(), v.end(), std::locale("ru_RU.UTF8"));
    assert(v[0] == L"был");
    assert(v[1] == L"жил");
    assert(v[2] == L"кот");
}

参阅

定义字典序比较和字符串的散列
(类模板)