std :: map关键类需要什么要求才能成为有效的密钥? [英] What requirements must std::map key classes meet to be valid keys?

查看:120
本文介绍了std :: map关键类需要什么要求才能成为有效的密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将给定类的对象映射到另一个对象。然而,我想用作键的类不是由我写的,而是一个简单的 struct ,其中有几个值。 std :: map命令它的内容,我想知道它是如何做的,如果任何类可以用作键,或者有一组要求(运算符和什么不需要)需要定义。



如果是这样,我可以为实现运营商地图使用的类创建一个包装器。我只需要知道我需要实现的第一个,而且我没有一个引用的类别我

所需要的所有关键是它是可复制和可分配的。
地图中的排序由
模板的第三个参数(以及构造函数的参数(如果使用))定义。这个
默认为 std :: less< KeyType> ,默认为< operator,
,但不需要使用默认值。只需写一个比较
运算符(最好作为一个功能对象):

  struct CmpMyType 
{
bool operator()(MyType const& lhs,MyType const& rhs)const
{
// ...
}
};

请注意,它必须定义严格的排序,即如果 CmpMyType() a,b
返回true,然后 CmpMyType()(b,a)必须返回false,如果
都返回false,元素被认为是相等的(
的成员相同的等价类)。


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.

解决方案

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
    {
        //  ...
    }
};

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).

这篇关于std :: map关键类需要什么要求才能成为有效的密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆