問題描述
我想將給定類的對象映射到另一個類的對象.然而,我想用作鍵的類不是我寫的,它是一個簡單的 struct
和幾個值.std::map 對它的內(nèi)容進行排序,我想知道它是如何做到的,以及是否可以將任意類用作鍵,或者是否需要定義一組要求(運算符等等).
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.
如果是這樣,我可以為實現(xiàn)運算符映射使用的類創(chuàng)建一個包裝器.我只需要知道我需要首先實現(xiàn)什么,并且沒有任何引用我 在線找到指定它們.
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.
推薦答案
密鑰所需要的只是它是可復(fù)制和可分配的.映射中的排序由第三個參數(shù)定義模板(以及構(gòu)造函數(shù)的參數(shù),如果使用的話).這個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
{
// ...
}
};
注意它必須定義一個嚴(yán)格的排序,即如果 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).
這篇關(guān)于std::map 鍵類必須滿足哪些要求才能成為有效鍵?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!