1. 程式人生 > >stl的map和hash_map簡單例子

stl的map和hash_map簡單例子

一:環境:linux g++

二:程式碼:

#include <map>
#include <ext/hash_map>
#include <iostream>
#include <string.h>

using namespace std;
using namespace __gnu_cxx;

struct hash_key_t
{
    hash_key_t(int _id, int _val) : id(_id), val(_val){}
    int id = 0;
    int val = 0;

    // hash_map 的key為自定義結構需要過載==
    bool operator ==(const hash_key_t& p) const
    {
        return (id == p.id) && (val == p.val);
    }
};

struct hash_func_t
{
    // 自定義的雜湊函式
    size_t operator()(const hash_key_t& p1) const
    {
        size_t key = ~p1.id + (p1.id << 15); // key = (key << 15) - key - 1;
        key = key ^ (key >> 12);
        key = key + (key << 2);
        key = key ^ (key >> 4);
        key = key * 2057; // key = (key + (key << 3)) + (key << 11);
        key = key ^ (key >> 16);
        return key;
    }
};

void TestHashMap()
{
    std::cout << "---- TestHashMap com_hash_map ---\n";
    hash_map<int, string> com_hash_map;
    com_hash_map.insert(std::make_pair(100, "Hello"));
    com_hash_map.insert(std::make_pair(101, "World"));

    for (auto& elem : com_hash_map)
    {
        std::cout << "First: " << elem.first << ", Second: " << elem.second << std::endl;
    }
    std::cout << "---- TestHashMap def_hash_map ---\n";
    hash_map<hash_key_t, string, hash_func_t> def_hash_map;
    hash_key_t k1(1, 100), k2(2, 200);
    def_hash_map.insert(std::make_pair(k1, "Fine"));
    def_hash_map.insert(std::make_pair(k2, "Tks"));
    for (auto& elem : def_hash_map)
    {
        std::cout << "First: " << elem.first.id << ", " << elem.first.val << ", Second: " << elem.second << std::endl;
    }
}

struct map_key_t
{
    map_key_t(int _id, int _val) : id(_id), val(_val){}
    int id = 0;
    int val = 0;

    // map的key為自定義結構需要過載<
    bool operator <(const map_key_t& p) const
    {
        return (id < p.id) || (id == p.id && val < p.val);
    }
};

void TestMap()
{
    std::cout << "---- TestMap --- com_map \n";
    std::map<int, string> com_map;
    com_map.insert(std::make_pair(100, "Leon"));
    com_map.insert(std::make_pair(101, "Lucifer"));
    for (auto& elem : com_map)
    {
        std::cout << "First: " << elem.first << ", Second: " << elem.second << std::endl;
    }

    std::cout << "---- TestMap --- key_map \n";
    map_key_t k1(1, 100), k2(1, 110),k3(10, 99);
    std::map<map_key_t, string> key_map;
    key_map.insert(std::make_pair(k1, "Leon"));
    key_map.insert(std::make_pair(k2, "Lucifer"));
    key_map.insert(std::make_pair(k3, "Lucy"));

    for (auto& elem : key_map)
    {
        std::cout << "First: " << elem.first.id << ", " << elem.first.val << ", Second: " << elem.second << std::endl;
    }
}

int main(void)
{
    TestHashMap();
    TestMap();
    return 0;
}

三:執行結果