【基础】结构体重载,用 char*作为std::map中的key

结构体重载

C++中,结构体是无法进行==,>,<,>=,<=,!=这些操作的,这也带来了很多不方便的地方,尤其是在使用STL容器的时候,如果我们可以往语句中传入结构体,一些事情将会变得很简单。
 
bool operator 运算符 (const 结构体名称 b) const
{
    return(什么时候这个运算符对结构体成立);//注意对此运算符使用this->元素名;
}

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

首先为什么要用 char*作为std::map中的key

map<char*,int>和map<string,int>在插入和存储效率的对比。
                                        插入100000条                    查询100000次
map<string,int>              119ms                                  89ms     
map<char*,int>               9ms                                      6ms
 
声明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;

}

参考博客:
用 char*作为std::map中的key

map<char*,int>和map<string,int>的效率对比? 

猜你喜欢

转载自www.cnblogs.com/Kohinur/p/8977263.html
今日推荐