我想将
unordered map
与自定义Key
类一起使用:
#include <iostream>
#include <unordered_map>
using namespace std;
class Item
{
private:
std::string m_ItemId;
int m_Price;
int m_Count;
public:
Item(std::string id, int price, int count): m_ItemId(id), m_Count(count), m_Price(price){}
int getCount() const { return m_Count;}
std::string getItemId() const { return m_ItemId;}
int getPrice() const { return m_Price;}
};
class Key
{
int m_value;
public:
Key(int val) :m_value(val){}
int getValue() const {return m_value;}
};
struct Compare
{
size_t operator()(const Key& a, const Key& b) const
{
return a.getValue() < b.getValue();
}
};
unordered_map<Key, Item, Compare> getItemList()
{
unordered_map<Key, Item,Compare> mapOfItems ;
mapOfItems.insert(std::make_pair(Key(1), Item("D121",100,2)));
mapOfItems.insert(std::make_pair(Key(8), Item("D122",12,5)));
mapOfItems.insert(std::make_pair(Key(6), Item("D125",99,3)));
mapOfItems.insert(std::make_pair(Key(3), Item("D123",28,6)));
mapOfItems.insert(std::make_pair(Key(2), Item("D125",99,3)));
return mapOfItems;
}
int main()
{
unordered_map<Key, Item, Compare> mp = getItemList();
return 0;
}
我有一个编译错误:
错误:静态断言失败:必须使用键类型的参数调用哈希函数
你能帮帮我吗?
要理解的是,基本上
std::unordered_map
就是标准库所说的哈希表。它是一个“无序”容器,而不是基于比较的关联容器,例如红黑树(std::map
的典型实现)。
它的第三个模板参数是一个散列函数对象,而不是一个比较函数对象。 (然而它的第四个模板参数是一个类似比较的函数对象,一个相等性检查函数,因为哈希表实现需要测试相等性以解决哈希冲突等)如下:
// ...
struct KeyHasher
{
size_t operator()(const Key& a) const
{
return std::hash<int>{}(a.getValue());
}
};
struct KeyEquals
{
bool operator()(const Key& a, const Key& b) const
{
return a.getValue() == b.getValue();
}
};
unordered_map<Key, Item, KeyHasher, KeyEquals> getItemList()
{
unordered_map<Key, Item, KeyHasher, KeyEquals> mapOfItems;
mapOfItems.insert(std::make_pair(Key(1), Item("D121", 100, 2)));
mapOfItems.insert(std::make_pair(Key(8), Item("D122", 12, 5)));
mapOfItems.insert(std::make_pair(Key(6), Item("D125", 99, 3)));
mapOfItems.insert(std::make_pair(Key(3), Item("D123", 28, 6)));
mapOfItems.insert(std::make_pair(Key(2), Item("D125", 99, 3)));
return mapOfItems;
}
int main()
{
unordered_map<Key, Item, KeyHasher, KeyEquals> mp = getItemList();
return 0;
}