如何强制std :: map :: find()按值搜索

时间:2013-04-14 20:27:49

标签: c++

根据我的推断,std :: map :: find()方法通过比较指针地址而不是值来搜索地图。例如:

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
}

我有点惊讶(因为我使用原始类型而不是某些类)我认为我做错了,如果不是,那么如何强制它使用值而不是地址?

2 个答案:

答案 0 :(得分:8)

您使用char *作为地图的关键字类型。对于指针类型,比较由它们的地址执行(因为map不能知道这些指针是以NULL结尾的8位字符串)。

为了实现目标,您可以使用自定义map功能创建compare,例如:

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

或者考虑使用std::string作为密钥类型。

答案 1 :(得分:4)

实际上,map使用严格的排序比较运算符来查找值,而不是相等运算符。无论如何,你可以通过传递一个比较字符串值的自定义函子来做到这一点,或者做正确的事情并改用std::string