c++ 错误:使用删除的函数'std::unordered_map'与Key类

tquggr8v  于 2023-04-01  发布在  其他
关注(0)|答案(1)|浏览(383)

我想将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;
}

我有一个编译错误:
错误:静态Assert失败:散列函数必须可使用键类型的参数调用
你能帮帮我吗?

2ul0zpep

2ul0zpep1#

需要理解的是,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;
}

相关问题