链表实现哈希表编译报错:数组/vector替换仍失效,疑与模板相关
链表实现哈希表编译错误解决
我尝试用链表实现哈希表,但编译报错。试过用数组替代vector,问题依旧。怀疑和模板有关,但看不懂相关模板示例。以下是复现代码和错误信息:
#include <iostream> #include <vector> using namespace std; struct node { string key; string value; node* next; }; class HashTable { private: vector<node*> bucket; long long int capacity; public: HashTable(long long int max_size = 100) { capacity = max_size; bucket.reserve(capacity); bucket.resize(capacity); fill(bucket.begin(), bucket.end(), NULL); } };
编译错误信息:
Build started... 1>------ Build started: Project: C++ Test, Configuration: Debug x64 ------ 1>C++ Test.cpp 1>E:\Other\Visual Studio\VC\Tools\MSVC\14.33.31629\include\xutility(4519,24): error C2440: '=': cannot convert from 'const _Ty' to 'node *' 1> with 1> [ 1> _Ty=int 1> ] 1>E:\Other\Visual Studio\VC\Tools\MSVC\14.33.31629\include\xutility(4519,24): message : Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or parenthesized function-style cast 1>C:\Users\DaLaw2\source\repos\C++ Test\C++ Test.cpp(30): message : see reference to function template instantiation 'void std::fill<std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>,int>(const _FwdIt,const _FwdIt,const int &)' being compiled 1> with 1> [ 1> _Ty=node *, 1> _FwdIt=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<node *>>> 1> ] 1>Done building project "C++ Test.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
问题原因
错误核心是NULL在C中被定义为整数0,而你要填充的是node*指针类型。C不允许隐式将整数转换为指针,因此触发类型转换错误。
解决方法
方法1:使用nullptr替代NULL
nullptr是C++11及以后标准中专门用于表示空指针的关键字,类型为std::nullptr_t,可以安全转换为任意指针类型。修改构造函数中的fill调用:
fill(bucket.begin(), bucket.end(), nullptr);
方法2:简化代码,去掉冗余的fill调用
调用bucket.resize(capacity)时,vector会自动将新元素默认初始化为nullptr(指针类型的默认初始化就是空指针),因此可以直接删除fill行,简化构造函数:
HashTable(long long int max_size = 100) { capacity = max_size; bucket.resize(capacity); // 自动初始化所有元素为nullptr }
数组替代vector的情况
如果用数组实现,同样需要把NULL换成nullptr,避免整数到指针的隐式转换错误。
内容的提问来源于stack exchange,提问作者DaLaw2
相关产品推荐
相关产品推荐

