zoukankan      html  css  js  c++  java
  • [C++]unordered_map的使用

    unordered_map和map类似,都是存储的key-value的值,可以通过key快速索引到value。

    不同的是unordered_map不会根据key的大小进行排序,存储时是根据key的hash值判断元素是否相同,即unordered_map内部元素(key)是无序的,而map中的元素是按照二叉搜索树存储,进行中序遍历会得到有序遍历。

    所以使用时map的key需要定义operator<。而unordered_map需要定义hash_value函数并且重载operator==。但是很多系统内置的数据类型都自带这些,那么如果是自定义类型,那么就需要自己重载operator<或者 hash_value()了。

    结论:如果需要内部元素自动排序,使用map,不需要排序使用unordered_map。

    C++11为什么不把unordered_map定义为hash_map呢?那是因为在新标准出现之前很多库厂商已经暂用了hash_map这个名词。因此为了向前兼容不得不定义新的unordered_map。

    所以unordered_map就是一个hash_table,类似一个用数组模拟的hash_table。但是要注意两个经常使用的函数:

    find函数,在查找失败的时候返回map.end(),最后一个元素后面的一个仅仅起到标志作用的元素。

    iterator find ( const key_type& k );
    const_iterator find ( const key_type& k ) const;
    Get iterator to element
    Searches the container for an element with k as key and returns an iterator to it if found,
    otherwise it returns an iterator to unordered_map::end (the element past the end of the container).

    operator[]访问函数,这个可以根据key操作对应的value,跟数组模拟的hash_table使用一样。

    mapped_type& operator[] ( const key_type& k );
    mapped_type& operator[] ( key_type&& k );
    Access element
    If k matches the key of an element in the container, 
    the function returns a reference to its mapped value.
    
    If k does not match the key of any element in the container, 
    the function inserts a new element with that key and returns a reference to its mapped value. 
    Notice that this always increases the container size by one, even if no mapped value is assigned to the element
    (the element is constructed using its default constructor).
    

      

      

  • 相关阅读:
    local variable 'xxx' referenced before assignment(犯过同样的错)
    combobox后台查询,前端下拉显示
    查询时,模糊显示结果
    jgrid label时间格式化显示
    解决:dubbo找不到dubbo.xsd报错
    关于jsp页面下,重置选择框的数据的操作!
    关于return返回
    cmd下调用jar
    关于前台查询时,查询条件不同时,garitable域数据展示不同,这里要实现功能要做empty()操作,缓存问题。
    Python3练习题系列(10)——项目骨架构建
  • 原文地址:https://www.cnblogs.com/stemon/p/4819973.html
Copyright © 2011-2022 走看看