title: How can I use a std::map with std::weak_ptr as key?
body: <p>How can I use <code>std::weak_ptr</code> as key for a <code>std::map</code> as shown in the following code?</p>
  
  <pre><code>#include &lt;map&gt;
  #include &lt;memory&gt;
  
  int main()
  {
      std::map&lt; std::weak_ptr&lt;int&gt;, bool &gt; myMap;
  
      std::shared_ptr&lt;int&gt; sharedptr(new int(5));
      std::weak_ptr&lt;int&gt; weakptr = sharedptr;
  
      myMap[weakptr] = true;
  
      return 0;
  }
  </code></pre>
  
  <p>The above program doesn't build and trying to compile it gives many error messages such as:</p>
  
  <pre><code>1&gt;C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xfunctional(125): error C2784: 'bool std::operator &lt;(const std::_Tree&lt;_Traits&gt; &amp;,const std::_Tree&lt;_Traits&gt; &amp;)' : could not deduce template argument for 'const std::_Tree&lt;_Traits&gt; &amp;' from 'const std::tr1::weak_ptr&lt;_Ty&gt;'
  1&gt;          with
  1&gt;          [
  1&gt;              _Ty=int
  1&gt;          ]
  1&gt;          C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xtree(1885) : see declaration of 'std::operator &lt;'
  1&gt;          C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xfunctional(124) : while compiling class template member function 'bool std::less&lt;_Ty&gt;::operator ()(const _Ty &amp;,const _Ty &amp;) const'
  1&gt;          with
  1&gt;          [
  1&gt;              _Ty=std::tr1::weak_ptr&lt;int&gt;
  1&gt;          ]
  1&gt;          C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\map(71) : see reference to class template instantiation 'std::less&lt;_Ty&gt;' being compiled
  1&gt;          with
  1&gt;          [
  1&gt;              _Ty=std::tr1::weak_ptr&lt;int&gt;
  1&gt;          ]
  1&gt;          C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xtree(451) : see reference to class template instantiation 'std::_Tmap_traits&lt;_Kty,_Ty,_Pr,_Alloc,_Mfl&gt;' being compiled
  1&gt;          with
  1&gt;          [
  1&gt;              _Kty=std::tr1::weak_ptr&lt;int&gt;,
  1&gt;              _Ty=bool,
  1&gt;              _Pr=std::less&lt;std::tr1::weak_ptr&lt;int&gt;&gt;,
  1&gt;              _Alloc=std::allocator&lt;std::pair&lt;const std::tr1::weak_ptr&lt;int&gt;,bool&gt;&gt;,
  1&gt;              _Mfl=false
  1&gt;          ]
  </code></pre>
  
  <p>The problem occurs due to the following line:</p>
  
  <pre><code>myMap[weakptr] = true;
  </code></pre>
  
  <p>The error messages seem to be related to <code>operator&lt;</code>. Do I need to define <code>operator&lt;</code> for <code>weak_ptr</code>? Exactly, what operators need to be defined in order to use a data type as a key for a <code>std::map</code>?</p>
  
  <p>(I should note that I have already defined <code>operator==</code> in the <code>std</code> namespace. Also, I plan to use a <code>weak_ptr</code> to a custom class type and not an <code>int</code>.)</p>