tobi
tobi

Reputation: 2012

How to force std::map::find() to search by value

From what I have deduced, the std::map::find() method searches the map by comparising pointer address instead of values. Example:

std::string aa = "asd";
const char* a = aa.c_str();
const char* b = "asd";
// m_options is a std::map<const char*, int )
m_options.insert( std::make_pair( a, 0 ) );
if( m_options.find( b ) != m_options.end() ) {
    // won't reach this place
}

I am kinda surprised (because I am using primitive types instead of some class) and I think that I have done something wrong, if not then how to force it to use value instead of address?

Upvotes: 0

Views: 241

Answers (2)

nullptr
nullptr

Reputation: 11058

You are using char * as a key type for the map. For the pointer types, comparison is performed by their address (as the map cannot know that these pointers are NULL-terminated 8-bit strings).

To achieve your goal, you could create the map with custom compare function, e.g.:

bool MyStringCompare(const char *s1, const char *s2) { 
  return strcmp(s1, s2) < 0; 
}
...
std::map<const char*, int, MyStringCompare> m_options;

Or consider using std::string as the key type.

Upvotes: 8

Luchian Grigore
Luchian Grigore

Reputation: 258678

Actually, map uses a strict ordering comparison operator to look for values, not the equality operator. Anyway, you can achieve this by passing a custom functor that compares the values of the strings, or do the right thing and use std::string instead.

Upvotes: 4

Related Questions