Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing an std::string as a key for an std::map
    primarykey
    data
    text
    <p>I would like to have an std::map (int .NET 4.0). We of course know that a map is a tree and requires an operator&lt; that string does not define for us. </p> <blockquote> <p>Error 24 error C2676: binary '&lt;' : 'const std::string' does not define this operator or a conversion to a type acceptable to the predefined operator c:\program files\microsoft visual studio 10.0\vc\include\xfunctional 125 1 FXCMMarketDataServer</p> </blockquote> <p>So I put my google-foo to work and found this solution:</p> <pre><code>struct StringComparerForMap { public: bool operator()(const std::string x, const std::string y) { // Add compare logic here } }; ... std::map&lt;std::string, CustomObject, StringComparerForMap&gt; myMap; </code></pre> <p>This worked fine for a while, and now I'm encountering a bug that I believe is due to this. Somewhere deep down in the STL framework it would seem that it ignores the above definition and defaults to operator&lt;.</p> <p>Is there a way in VS2010 .NET 4.0 to use a string as the key of a map?</p> <p>I understand that I can take that string and write a function to hash it to an int, but where's the fun in that?</p> <p><strong>EDIT</strong></p> <p>I will try and explain this as best I can for David. When the map uses the comparer struct, it crashes in release and fails a debug assertion in debug. The assert that fails is in xtree line 1746. </p> <blockquote> <p>Expression: invalid operator&lt;</p> <p>|Abort| |Retry| |Ignore|</p> </blockquote> <p>That is what leads me to believe that despite giving map a comparer, it still down certain paths defaults to operator&lt; for comparison. The line in my code that causes this is:</p> <pre><code>CustomObject o = stringObjectMap[key]; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload