C++ map和unordered_map自定义key

1、map

1)最简单的方法就是实现该自定义类型的<操做符,代码以下:

class Foo
{
public:
    Foo(int num_)
        : num(num_)
    {
    }
    bool operator < (const Foo & cmp) const
    {
        return num < cmp.num;
    }  
    int num;   
};

以后就能够使用Foo做为map的key了:html

map<Foo, int> dict;
dict[Foo(1)] = 1;

2)定义一个比较操做符,使用它做为map的模板参数,代码以下:

typedef std::pair<Foo, int> Foo2;
class Foo2Comparator
{
public:
    bool operator()(const Foo2& key1, const Foo2& key2) const
    {
        if (key1.first < key2.first)
        {
            return true;
        }
        else if (key2.first < key1.first)
        {
            return false;
        }
        else
        {
            return key1.second < key2.second;
        }
    }
};

这时候能够使用Foo2做为map的key了:less

map<Foo2, int, Foo2Comparator> dict2;
dict2[Foo2(Foo(1), 100)] = 1;

3)为用户自定义类型特化std::less,代码以下:

namespace std
{
    template <>
    struct less<Foo2>
        : public binary_function <Foo2, Foo2, bool>
    {
        bool operator()(const Foo2& key1, const Foo2& key2) const
        {
            if (key1.first < key2.first)
            {
                return true;
            }
            else if (key2.first < key1.first)
            {
                return false;
            }
            else
            {
                return key1.second < key2.second;
            }
        }
    };
}

使用这种方法,声明map时无需指定比较函数对象,由于默认的比较对象就是std::less<T>ide

map<Foo2, int> dict2;
dict2[Foo2(Foo(1), 100)] = 3;

2、unordered_map

        当试图使用自定义类型做为 unordered_map 的键值时,则必须为自定义类型定义 Hash 函数与相等的判断条件。咱们先定义自定义类型做键值,代码以下:函数

struct KEY
{
	int first;
	int second;
	int third;

	KEY(int f, int s, int t) : first(f), second(s), third(t){}
};

1)Hash 函数

        必须为 override 了 operator() 的一个类,通常自定义类型可能包含几种内置类型,咱们能够分别计算出内置类型的 Hash Value 而后对它们进行 Combine 获得一个哈希值,通常直接采用移位加异或(XOR)即可获得还不错的哈希值(碰撞不会太频繁),以下:spa

struct HashFunc
{
	std::size_t operator()(const KEY &key) const 
	{
		using std::size_t;
		using std::hash;

		return ((hash<int>()(key.first)
			^ (hash<int>()(key.second) << 1)) >> 1)
			^ (hash<int>()(key.third) << 1);
	}
};

2)相等函数

        哈希须要处理碰撞,意味着必须得知道两个自定义类型对象是否相等,因此必须得提供比较相等的方法,能够 重载operator ==,能够用 std::equal,也能够实现一个 重写 operator () 的类,这里咱们采用后者,代码以下:code

struct EqualKey
{
	bool operator () (const KEY &lhs, const KEY &rhs) const
	{
		return lhs.first  == rhs.first
			&& lhs.second == rhs.second
			&& lhs.third  == rhs.third;
	}
};

下面为一个具体应用的例子:htm

int main()
{
	unordered_map<KEY, string, HashFunc, EqualKey> hashmap =
	{
		{ { 01, 02, 03 }, "one" },
		{ { 11, 12, 13 }, "two" },
		{ { 21, 22, 23 }, "three" },
	};

	KEY key(11, 12, 13);

	auto it = hashmap.find(key);
	
 	if (it != hashmap.end())
 	{
 		cout << it->second << endl;
 	}

	return 0;
}

参考资料:对象

http://blog.sina.com.cn/s/blog_48d4cf2d0100mx4t.htmlblog

http://www.ithao123.cn/content-10629313.htmlthree

相关文章
相关标签/搜索