zoukankan      html  css  js  c++  java
  • 【基础】结构体重载,用 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>的效率对比? 

  • 相关阅读:
    For each···in / For···in / For···of
    JavaScript object
    specific word count (index of )
    history of program
    js的回调函数
    promise
    js的事件流事件机制
    js的closures(闭包)
    baidu-map
    基于封装优点的类设计习惯
  • 原文地址:https://www.cnblogs.com/Kohinur/p/8977263.html
Copyright © 2011-2022 走看看