什么要求必须std :: map键类满足才是有效的键? [英] What requirements must std::map key classes meet to be valid keys?

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

问题描述

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

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.

如果是这样,我可以为实现运算符map使用的类创建一个包装器。我只需要知道我需要首先实现,没有一个参考资料在线找到指定它们。

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.

推荐答案

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

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

请注意,它必须定义一个严格的排序,即if CmpMyType a,b
返回true,则 CmpMyType()(b,a)必须返回false,如果
两个返回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).

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

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