声明map时需要添加一个cmp比较函数,不然map在比较时,使用char *的指针进行比较,而不是比较char字符串。
#include <cstring>
struct cmp_str
{
bool operator()(char const *a, char const *b)
{
return std::strcmp(a, b) < 0;
}
};
int main ( int argc, char ** argv )
{
std::map<const char*, int, cmp_str> map;
map["aa"] = 1;
map["ca"] = 2;
map["ea"] = 3;
map["ba"] = 4;
map["ba"] = 5;
map["bb"] = 6;
map["ba"] = 7;
std::map<const char*, int, cmp_str>::iterator it = map.begin();
for (; it != map.end(); it++ )
{
std::cout << (*it).first << ": " << (*it).second << std::endl;
}
return 0;
}
参考:
http://stackoverflow.com/questions/4157687/using-char-as-a-key-in-stdmap