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;
}

三:运行结果

猜你喜欢

转载自blog.csdn.net/vitas_fly/article/details/82781003