与map和unordered_map相关的编译错误:“试图引用已删除的函数” [英] Compilation error related to map and unordered_map: "attempting to reference a deleted function"

查看:1420
本文介绍了与map和unordered_map相关的编译错误:“试图引用已删除的函数”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++ STL中使用map在vector和int之间创建关联。但是我在以下代码中遇到了多个编译错误:

I want to use map in C++ STL to create assosiation between vector and int. But I got multiple compilation error with code presented below:

#include <vector>
#include <map>
#include <unordered_map>

using namespace std;

int main(void)
{
    unordered_map<vector<char>, int> mp;
    return 0;
}

然后在VC ++中出现此编译错误:

And got this compilation error in VC++:

错误C2280:'std :: hash< _Kty> :: hash(const std :: hash< _Kty>&)':试图引用已删除的函数

error C2280: 'std::hash<_Kty>::hash(const std::hash<_Kty> &)': attempting to reference a deleted function

但是,如果我按如下所示更改代码,则可以正确编译代码:

However, if I change my code like presented below, then the code can be compiled properly:

#include <vector>
#include <map>
#include <unordered_map>

using namespace std;

int main(void)
{
    map<vector<char>, int> mp;
    return 0;
}

我在StackoverFlow中发现了这个问题,标题是:
C ++ unordered_map,使用自定义类类型作为键。
但是我想知道为什么使用map<>可以通过编译检查,但是不能通过unordered_map<>使用?

I have found this question asked in StackoverFlow, whose title is: C++ unordered_map using a custom class type as the key. But I wondered that why using map<> can pass the compilation check but unable with unordered_map<> ?

推荐答案

接下来是@JohnZwinck的(出色)答案,我想说的是将 std :: unordered_map vector 一起用作密钥通常不是一个好主意,因为实现任何一种有效的哈希函数的成本可能很高。

Following on from @JohnZwinck's (excellent) answer, I would say that using std::unordered_map with a vector as a key is usually a bad idea, because of the likely high cost of implementing any kind of effective hashing function.

John给出的链接对此进行了扩展,但从本质上讲,哈希函数必须在每次需要哈希任何内容时检查向量中的每个元素。如果向量很大,那么 ouch!

The link John gave expands on this, but, essentially, the hash function has to inspect every element in the vector every time anything needs to be hashed. If the vector is large, well, ouch!

所以 std :: map 可能是一个更好的选择,因为 std :: less (-> operator <)便宜-只要我们点击向量中两个操作数之间的值不同的元素,就完成了。最坏的情况是,它不再昂贵(尽管 std :: unordered_map 确实比 std :: map 当确实存在便宜且有效的哈希函数时,例如,如果键是类似 int )之类的东西。

So std::map is likely to be a better choice here, because std::less (-> operator<) is likely to be cheap - as soon as we hit an element of the vector whose value differs between the two operands, we are done. Worst case, it is no more expensive (although it's true that std::unordered_map is more efficient than std::map when a cheap and effective hashing function does exist, especially, for example, if the key is something like an int).

这篇关于与map和unordered_map相关的编译错误:“试图引用已删除的函数”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆