[英]Error with Hash Table in c++
I written a simple program for insert data in Hash Table and remove data from it with C++ language. 我编写了一个简单的程序,用于在哈希表中插入数据,并使用C ++语言从中删除数据。 My program error is: undefined reference to 'HashTable::insert(int&)' How to fix this error?
我的程序错误是: 对'HashTable :: insert(int&)'的未定义引用如何解决此错误?
#include <iostream>
#include <list>
#include <vector>
using namespace std;
I Create a template for give all variables. 我创建一个模板以提供所有变量。
template <typename HashedObj>
class HashTable {
public:
explicit HashTable(int cusize = 101) {}
bool contains(const HashedObj& x) const
{
auto& whichList = theLists[myhash(x)];
return find(begin(whichList), end(whichList), x) != end(whichList);
}
void makeEmpty()
{
for (auto& thisList : theLists)
thisList.clear();
}
bool insert(const HashedObj& x)
{
auto& whichList = theLists[myhash(x)];
if (find(begin(whichList), end(whichList), x) != end(whichList))
return false;
whichList.push_back(x);
//Rehash
if (++currentSize > theLists.size())
rehash();
return true;
}
bool insert(HashedObj& x);
bool remove(const HashedObj& x)
{
auto& whichList = theLists[myhash(x)];
auto itr = find(begin(whichList), end(whichList), x);
if (itr == end(whichList))
return false;
whichList.erase(itr);
--currentSize;
return true;
}
private:
vector<list<HashedObj>> theLists; //The array of Lists
int currentSize;
void rehash();
size_t myhash(const HashedObj& x) const
{
static hash<HashedObj> hf;
return hf(x) % theLists.size();
}
};
In the main function i create a HashTable with int variable for example and insert 10 number to it but compiler has a error on test = t.insert(i); 在主函数中,例如,创建一个带有int变量的HashTable并向其插入10号,但是编译器在test = t.insert(i)上出错。 for insert function.
用于插入功能。
int main()
{
HashTable<int> t;
bool test;
for (int i = 0; i < 10; i++) {
test = t.insert(i);
}
}
There seems to be two bool insert(params) functions in your code: 您的代码中似乎有两个bool insert(params)函数:
bool insert(const HashedObj& x)
{
auto& whichList = theLists[myhash(x)];
if (find(begin(whichList), end(whichList), x) != end(whichList))
return false;
whichList.push_back(x);
//Rehash
if (++currentSize > theLists.size())
rehash();
return true;
}
and here: 和这里:
bool insert(HashedObj& x);
Remove one of them. 删除其中之一。
Edit: As @DietmarKühl suggested, you should remove the second implementation. 编辑:如@DietmarKühl建议,您应该删除第二个实现。
You declared two insert
functions, the first one took a const HashedObj&
parameter, the second one took a HashedObj&
parameter. 您声明了两个
insert
函数,第一个函数使用const HashedObj&
参数,第二个const HashedObj&
使用HashedObj&
参数。
test = t.insert(i);
i
is a non-const variable here, so it matches the second insert function, but you didn't implement it. i
在这里是一个非常量变量,因此它与第二个insert函数匹配,但是您没有实现它。
It could work well if you remove the second insert
declaration, because the compiler will convert i
to a const int&
type automaticlly. 如果删除第二个
insert
声明,它可能会很好地工作,因为编译器会自动将i
转换为const int&
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.