我尝试环顾四周并尝试了所有解决方案,但我似乎无法解决我的问题。我知道我在 push_front 线上遇到了段错误,但我只是迷路了。这是代码-
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
using namespace std;
typedef std::list<int> hSlots; //the list
typedef hSlots* hTable; //an array of lists
class HashTable
{
private:
int p; //p=number of slots in the hash table
hTable tmpPtr;
hTable *table;
public:
HashTable(int p1);
int h1(int k);
~HashTable();
void chainedHashInsert(int x);
};
HashTable::HashTable(int p1)
{
p=p1;
hTable tTable[p];
//initializing to empty lists
for (int i=0; i<p; i++)
{
tmpPtr = new hSlots;
tTable[i] = tmpPtr;
}
table = tTable;
}
//destrcutor
HashTable::~HashTable()
{
delete table;
delete tmpPtr;
}
void HashTable::chainedHashInsert(int x)
{
tmpPtr = table[h1(x)];
cout<<"hashed"<<endl;
tmpPtr->push_front(x); //segmentation fault
}
int HashTable::h1(int k)
{
int z = k%p;
return z;
}
我没有使用很多列表,所以我不太确定
最佳答案
也许这毕竟是一个正确的答案。
您的问题是由于在 C++ 中手动进行内存管理(错误)而产生的,而实际上没有必要这样做。
这是我在 C++ 中使用直接自动内存管理的看法:
#include <vector>
#include <list>
using namespace std;
template <typename T, typename hSlots = std::list<T> >
class HashTable
{
private:
int p; //p=number of slots in the hash table
std::vector<hSlots> table;
int getbucket(int k) { return k%p; }
public:
HashTable(int p1) : p(p1), table(p1) {}
void chainedHashInsert(int x)
{
auto& tmpPtr = table[getbucket(x)];
tmpPtr.push_front(x);
}
};
int main()
{
HashTable<int> table(37);
}
关于c++ - Push_front 段错误 11 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15181552/