与映射和unordered_map相关的编译错误:"attempting to reference a deleted function"
Compilation error related to map and unordered_map: "attempting to reference a deleted function"
我想在 STL 中使用 map C++在向量和 int 之间创建关联。但是我遇到了多个编译错误,代码如下所示:
#include <vector>
#include <map>
#include <unordered_map>
using namespace std;
int main(void)
{
unordered_map<vector<char>, int> mp;
return 0;
}
并在VC++中出现此编译错误:
错误 C2280:"std::hash<_Kty>::hash(const std::hash<_Kty> &(":尝试引用已删除的函数
但是,如果我像下面介绍的那样更改我的代码,那么代码可以正确编译:
#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<> ?
map
要求实现小于比较。 它是什么,对于一个向量。 但是unordered_map
需要一个哈希函数,你需要自己实现。 这没什么大不了的,你可以在这里看到如何使用hash_combine
来做到这一点:'std::vector' 的快速哈希函数
继@JohnZwinck(优秀(的回答之后,我会说使用带有vector
的std::unordered_map
作为键通常是一个坏主意,因为实现任何类型的有效哈希函数的成本都可能很高。
John 给出的链接对此进行了扩展,但本质上,哈希函数必须在每次需要散列任何内容时检查向量中的每个元素。 如果矢量很大,好吧,哎哟!
所以std::map
在这里可能是更好的选择,因为std::less
(->operator<
(可能很便宜 - 一旦我们命中两个操作数之间值不同的向量元素,我们就完成了。 最坏的情况是,它并不昂贵(尽管当确实存在廉价有效的哈希函数时,std::unordered_map
确实比std::map
更有效,特别是,例如,如果密钥是类似int
的东西(。
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- C++ Singleton - Prevent ::instance() to variable
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- Visual Studio Code "undefined reference to `WinMain@16'"
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 如何解决"invalid conversion from 'char' to 'const char*'"
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- Python str to C++ to Python str
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 不断"Attempting to reference a deleted function"
- 与映射和unordered_map相关的编译错误:"attempting to reference a deleted function"
- 将 QMutex 添加到类后的"Attempting to reference a deleted function"
- C++:具有 const int 的类的 vector.erase 实例给出"attempting to reference a deleted function"错误 C2280
- "attempting to reference a deleted function"函数参数
- 错误 "Attempting to reference a deleted function" - 传回 unique_ptr 的值时
- 尝试使用 std::bind 重新分配 std::function 并得到错误"attempting to reference a deleted function"
- 我怎么知道"C2280 - attempting to reference a deleted function"发生在哪里?
- "Attempting to reference a deleted function"