title: Is NaN a valid key value for associative containers?
body: <p>Consider the ordered and unordered associative containers in C++ keyed on <code>double</code>.</p>
  
  <p>Is <code>NaN</code> a valid key type?</p>
  
  <p>With ordered containers, I should say "no", because it does not respect the strict weak ordering.</p>
  
  <p>With unordered containers, I have no idea.</p>
  
  <p>Here's what happens in GCC 4.6.2:</p>
  
  <pre><code>#include &lt;map&gt;
  #include &lt;unordered_map&gt;
  
  #include &lt;cmath&gt;
  
  #include &lt;iostream&gt;
  #include &lt;prettyprint.hpp&gt;
  
  int main()
  {
    typedef std::map&lt;double, int&gt; map_type; // replace by "unorderd_map"
  
    map_type dm;
    double d = std::acos(5); // a good nan
  
    dm[d] = 2;
    dm[d] = 5;
    dm[d] = 7;
  
    std::cout &lt;&lt; "dm[NaN] = " &lt;&lt; dm[d] &lt;&lt; ", dm = " &lt;&lt; dm &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>For the ordered map, I get:</p>
  
  <pre><code>dm[NaN] = 7, dm = [(nan, 7)]
  </code></pre>
  
  <p>For the unordered map, I get:</p>
  
  <pre><code>dm[NaN] = 0, dm = [(nan, 0), (nan, 7), (nan, 5), (nan, 2)]
  </code></pre>
  
  <p>So in the ordered map, all NaNs are treated the same, which is what I expect, although it seemed like NaN would violate the requirements. For the unordered map, however, I can never retrieve an element again, and all NaNs are different. This is also not what I would expect.</p>
  
  <p>Does the standard have to say anything on this matter?</p>
  
  <p><strong>Update:</strong> Thanks to the great answers below, note that the <code>std::map</code> will break if you insert <em>anything else</em> into it once a NaN is in it.</p>
  
  <p>(I'd be very grateful for comments on how other languages handle floating point keys in associative containers.)</p>