问题描述
我想将给定类的对象映射到另一个类的对象.然而,我想用作键的类不是我写的,它是一个简单的 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).
这篇关于std::map 键类必须满足哪些要求才能成为有效键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)