unordered_map的用法

原博客:https://www.cnblogs.com/aaronzlq/p/3612629.html

C++11引入了很多新特性,比如auto ,比如 for(type v : container)等。

数据结构方面最抢眼的应该是引入了unordered_set和unordered_map。比起普通的set 和 map,其内部不再是红黑树排关键字了,而是用的哈系表;来提高查找效率。

不过对于结构体的存储和映射,却没怎么发现别人讲,刚看了篇文章学会了=_=:http://choorucode.com/2012/06/26/c-using-unordered_set/

Mark一下,贴下自己的代码,也方便别人查使用方法。

g++ 编译时注意添加: -std=c++11

#include <iostream>
#include <cstdio>
#include <set>
#include <unordered_set>
#include <unordered_map>
using namespace std;

struct Node {
    Node(int _x, int _y):x(_x), y(_y) {}
    int x, y;
    bool operator == (const Node &t) const {
        return  x==t.x ;
    }
};
struct NodeHash {
    std::size_t operator () (const Node &t) const {
        return  t.x * 100 + t.y;
    }
};
unordered_set <Node, NodeHash> h_set;
unordered_map <Node, string, NodeHash> h_map;
int main(){
    unordered_map<Node,string,NodeHash>::iterator arr;
    h_set.insert(Node(1, 2));
    int x, y;
    cin >> x >> y;
    if(h_set.find(Node(x, y)) == h_set.end())
        cout << "Not found" << endl;
    else  cout << "Found succeed" << endl;
    h_map[Node(1, 2)] = "World";
    cout << h_map[Node(1, 2)] << endl;
    return 0;
}

/*

输入: 1 2

输出:

1 2
Found succeed
World

*/

  

原文地址:https://www.cnblogs.com/lengsong/p/11482627.html