简体   繁体   中英

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?

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, eg:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM