Jam*_*nze 63
密钥所需要的只是它是可复制的和可分配的.映射中的排序由模板的第三个参数(以及构造函数的参数,如果使用)定义.该
默认到std::less<KeyType>,其默认为<运营商,但没有规定使用默认值.只需编写一个比较运算符(最好作为一个功能对象):
struct CmpMyType
{
bool operator()( MyType const& lhs, MyType const& rhs ) const
{
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
请注意,它必须定义严格的排序,即如果CmpMyType()( a, b
)返回true,则CmpMyType()( b, a )必须返回false,如果两者都返回false,则认为元素相等(同一等价类的成员).
BЈо*_*вић 22
您需要定义operator <,例如:
struct A
{
int a;
std::string b;
};
// Simple but wrong as it does not provide the strict weak ordering.
// As A(5,"a") and A(5,"b") would be considered equal using this function.
bool operator<(const A& l, const A& r )
{
return ( l.a < r.a ) && ( l.b < r.b );
}
// Better brute force.
bool operator<(const A& l, const A& r )
{
if ( l.a < r.a ) return true;
if ( l.a > r.a ) return false;
// Otherwise a are equal
if ( l.b < r.b ) return true;
if ( l.b > r.b ) return false;
// Otherwise both are equal
return false;
}
// This can often be seen written as
bool operator<(const A& l, const A& r )
{
// This is fine for a small number of members.
// But I prefer the brute force approach when you start to get lots of members.
return ( l.a < r.a ) ||
(( l.a == r.a) && ( l.b < r.b ));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37805 次 |
| 最近记录: |