Reputation:
I'm trying to keep information in std::map
. But I have a problem with find
:
typedef map<string, string, equal_to<string>> MAP_STRING2STRING;
....
MAP_STRING2STRING map;
MAP_STRING2STRING::const_iterator iter;
When I try to find key
, I get the following error:
iter = map.find(key);
What am I doing wrong?
This error appears only when I have something in map
.
Upvotes: 2
Views: 1627
Reputation: 227370
Your map has the wrong kind of comparison functor. You need strict weak ordering (less-than or greater-than type comparison), not equality. You can just omit the comparison functor parameter and use a less-than comparison for std::string
. This implements strict weak ordering via a lexicographical comparison of strings:
typedef map<string, string> MAP_STRING2STRING;
This is equivalent to
typedef map<string, string, less<string> > MAP_STRING2STRING;
Internally, the map uses the strict weak ordering comparison to both order itself, and determine whether two keys are the equal.
The third template parameter allows you to instantiate a map with a custom ordering criterion. For example, this would create a map with the reverse ordering of the one above:
typedef map<string, string, greater<string> > MAP_STRING2STRING;
Upvotes: 9
Reputation: 42924
If you want a simple map from std::string
to std::string
, just use map<string, string>
(drop that equal_to<string>
bogus "comparator").
Moreover, since you have a variable named "map
", this can cause conflict with the STL map
class. Either change the variable name (e.g. call it myMap
), or use the std::
namespace prefix for std::map
class:
typedef map<string, string> MAP_STRING2STRING;
....
MAP_STRING2STRING myMap;
In addition, since from the error message you are using VS2010, you can use the convenient auto
C++11 keyword, to avoid the "clutter" of MAP_STRING2STRING::const_iterator
, and just use:
auto iter = myMap.find(someKey);
Upvotes: 1