用 char*作为std::map中的key


声明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



猜你喜欢

转载自blog.csdn.net/yangyangye/article/details/42119461
今日推荐