std::map 键类必须满足哪些要求才能成为有效键?
我想将给定类的对象映射到另一个类的对象.然而,我想用作键的类不是我写的,它是一个简单的 struct
和几个值.std::map 对它的内容进行排序,我想知道它是如何做到的,以及是否可以将任意类用作键,或者是否需要定义一组要求(运算符等等).
I want to map objects of a given class to objects of another. The class I want to use as key, however, was not written by me and is a simple struct
with a few values. std::map orders it's contents, and I was wondering how it does it, and if any arbitrary class can be used as a key or if there's a set of requirements (operators and what not) that need to be defined.
如果是这样,我可以为实现运算符映射使用的类创建一个包装器.我只需要知道我需要首先实现什么,并且没有任何引用我 在线找到指定它们.
If so, I could create a wrapper for the class implementing the operators map uses. I just need to know what I need to implement first, and none of the references for the class I found online specify them.
推荐答案
密钥所需要的只是它是可复制和可分配的.映射中的排序由第三个参数定义模板(以及构造函数的参数,如果使用的话).这个defaults 为 std::less
,默认为 <
操作符,但没有要求使用默认值.写个对比运算符(最好作为功能对象):
All that is required of the key is that it be copiable and assignable.
The ordering within the map is defined by the third argument to the
template (and the argument to the constructor, if used). This
defaults to std::less<KeyType>
, which defaults to the <
operator,
but there's no requirement to use the defaults. Just write a comparison
operator (preferably as a functional object):
struct CmpMyType
{
bool operator()( MyType const& lhs, MyType const& rhs ) const
{
// ...
}
};
注意它必须定义一个严格的排序,即如果 CmpMyType()( a, b)
返回真,则 CmpMyType()( b, a )
必须返回假,如果两者都返回false,元素被认为是相等的(成员相同的等价类).
Note that it must define a strict ordering, i.e. if CmpMyType()( a, b
)
returns true, then CmpMyType()( b, a )
must return false, and if
both return false, the elements are considered equal (members of the
same equivalence class).
相关文章