码迷,mamicode.com
首页 > 编程语言 > 详细

c++ unordered_map 哈希表使用

时间:2018-05-19 21:57:01      阅读:360      评论:0      收藏:0      [点我收藏+]

标签:return   else   ++   map   contains   names   cout   find   iterator   

C++中的 unordered_map使用时通过键值对进行插入,并通过find(key)进行寻找键值是否存在。

//iterator find (key) : 找到则返回对应键值得迭代器
//没有找到则返回unordered_map::end.
// unordered_map::find

  if ( got == mymap.end() )
    std::cout << "not found";
  else
    std::cout << got->first << " is " << got->second;

不能插入重复元素,即具有同样键值(key)的元素。

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

int main()
{
    unordered_map<string, string> mymap = {
        {"house", "maison"},
        {"apple", "pomme"},
        {"apple", "pomme"},
        {"apple", "pomme1"},
        {"tree", "arbre"},
        {"book", "livre"},
        {"door", "porte"},
        {"grapefruit", "pamplemousse"}
    };
    unsigned n = mymap.bucket_count();

    cout << "mymap has "  << n << "buckets.\n";
    for(unsigned i = 0; i < n; i++)
    {
        cout << "bucket #" << i  << "contains: ";
        for(auto it = mymap.begin(i); it != mymap.end(i); ++it)
        {
            cout << "[" << it->first << ":" << it->second << "]";
        }
        cout << "\n";
    } 
    return 0;

}
/* 输出
*mymap has 11buckets.
*bucket #0contains: 
*bucket #1contains: [book:livre]
*bucket #2contains: [grapefruit:pamplemousse]
*bucket #3contains: [house:maison]
*bucket #4contains: 
*bucket #5contains: 
*bucket #6contains: 
*bucket #7contains: 
*bucket #8contains: 
*bucket #9contains: [apple:pomme]
*bucket #10contains: [door:porte][tree:arbre]

 */

 

c++ unordered_map 哈希表使用

标签:return   else   ++   map   contains   names   cout   find   iterator   

原文地址:https://www.cnblogs.com/Shinered/p/9061696.html

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