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).
    

      

      

  • 相关阅读:
    常见 PL.SQL 数据库操作
    PL/SQL常见设置--Kevin的专栏
    pl/sql编程
    添加List集合覆盖问题
    程序猿感情生活的那些事
    表达式树-理解与进阶
    白话神经网络
    EF Core 数据验证
    c#8内插逐字字符串增强功能
    我的新博客
  • 原文地址:https://www.cnblogs.com/stemon/p/4819973.html
Copyright © 2011-2022 走看看