Is NaN a valid key value for associative containers?

后端 未结 3 1006
刺人心
刺人心 2020-12-03 10:00

Consider the ordered and unordered associative containers in C++ keyed on double.

Is NaN a valid key type?

With ordered containers,

3条回答
  •  无人及你
    2020-12-03 10:42

    This is because

    std::less(NaN, NaN) == false
    

    Like you said, the weak total ordering (required for std::map<>) is ok, the equality (or equivalence, extra requirement for any hash-based container) isn't ok to satisfy the key requirements for the hash (unordered) map

    Irreflexivity   f(x, x) must be false. 
     Antisymmetry   f(x, y) implies !f(y, x) 
     Transitivity   f(x, y) and f(y, z) imply f(x, z). 
     Transitivity of equivalence     
    
             Equivalence (as defined above) is transitive: if x 
             is equivalent to y and y is equivalent to z, then x is 
             equivalent to z. (This     implies that equivalence does 
             in fact satisfy the mathematical definition of an equivalence 
             relation.)
    

    Seeing that for std::map, equivalence is when !less(a,b) && !less(b,a), I'd say all constraints are met.

提交回复
热议问题