I want to use unordered map
with a custom Key
class:
#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;
}
I have a compilation error :
error: static assertion failed: hash function must be invocable with an argument of key type
Can you help me, please?