zoukankan      html  css  js  c++  java
  • C++——map注意事项

    1. C++标准模块库STL中提供了两种基本的关联容器:set和map。其内部实现是都是采用红黑树,但不同的是,set中结点存储的是键值,map中结点存储的是<key,value>的键值对。在map中,由key查找value时,首先要判断map中是否包含key。如果不检查,直接返回map[key],可能会出现意想不到的行为。

    2. 如果map包含key,则map[key]返回key所对应value的引用;如果map不包含key,使用下标有一个危险的副作用,会在map中插入一个key的元素,value取默认值,并返回value的引用,这就是为什么当向map中插入一个元素时,map[key] = value是成立的。综上所述,map[key]总有返回值。

    3. map提供了两种方式,查看是否包含key,即使用成员函数count和find,对于map<Type1,Type2> m:

    • m.count(key):由于map不包含重复的key,因此m.count(key)取值为0,或者1,表示是否包含。
    • m.find(key):返回迭代器,判断是否存在。若存在则返回key对应结点的迭代器,否则返回m.end()

    4. 对于查找map中是否存在key,有下面两种写法:

    使用成员函数count:

    bool is_map_key_exist1(const map<int,int> &m, const int &key)
    {
        if(m.count(key) > 0)
            return true;
        return false;
    }

    使用成员函数find:

    bool is_map_key_exist2(const map<int,int> &m, const int &key)
    {
        if(m.find(key) != m.end())
            return true;
        return false;
    }

    5. 当需要进行赋值或查找key对应的值时,推荐使用find。

    例如:

    //map<int,int> m;
    //int key;
    auto it = m.find(key);
    if( it != m.end())
        return it->second;

    可以看到只进行了一次查找。

    若先使用count判断是否存在,再使用[]返回value,即:

    //map<int,int> m;
    //int key;
    if(m.count(key) > 0)
        return m[key];

    可以看到count和[]分别进行了一次查找,即两次查找。

    基于效率的考虑,我们推荐使用find。

    6. 对于STL中的容器,除了使用成员函数find返回迭代器外,还有泛型算法find(begin,end,target)查找目标。

    参考资料:

    • https://www.cnblogs.com/nzbbody/p/3409298.html
  • 相关阅读:
    BCD与ASCII码互转-C语言实现
    <<用法
    linux无锁化编程--__sync_fetch_and_add系列原子操作函数
    C中的volatile用法
    c++ k^1
    linux ftp使用相关
    linux应用程序启动时加载库错误问题
    kafka消费者脚本无法启动问题
    Django框架简介
    前端基础之Bootstrap
  • 原文地址:https://www.cnblogs.com/oddcat/p/10265539.html
Copyright © 2011-2022 走看看