码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-05-01 23:33:39      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:.com   sdn   clu   ++   std   一个   second   为什么   net   

结构体重载

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>的效率对比? 

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

标签:.com   sdn   clu   ++   std   一个   second   为什么   net   

原文地址:https://www.cnblogs.com/Kohinur/p/8977263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!