unordered_map簡單示例

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<list>
#include<set>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<string>
#include<cstdlib>
#include<algorithm>
#include<tr1/unordered_map>
using namespace std;
using namespace std::tr1;
/*
在c++11以前要使用unordered_map需要
#include<tr1/unordered_map>//在unordered_map之前加上tr1庫名,
using namespace std::tr1;//加上命名空間
c++11之後
#include<unordered_map>
*/
struct node{
    int x, y;
};
struct myHash{ //重載哈希函數
    size_t operator()(const node &b) const {
        size_t h = b.x * 10000 + b.y + 100000000;
        return h; //此處要注意,返回的是一個無符號整型,不能出現負數
    }
};
struct myEqual{ //重載==
    bool operator()(const node &a, const node &b) const {
        return a.x == b.x && a.y == b.y;
    }
};
int main(){
    unordered_map<node, int, myHash, myEqual> ump;
    node a, b;
    a.x = 1;
    a.y = 2;
    b.x = 1;
    b.y = 2;
    ump[a] = 6;
    puts(ump[b] == 6 ? "y" : "n");
    return 0;
}

其餘用法基本和map相同。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章