【发布时间】:2013-12-25 21:04:57
【问题描述】:
我不明白为什么我的程序会出现分段错误。谁能解释一下这个问题?
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
class HashTable {
private:
int *A[1];
int n;
int bsize;
vector<int> B;
public:
HashTable(int size) {
n = size;
bsize = 0;
*A = new int[n];
}
/*
You should use another array B besides A. You do not initialize A, and thus the cells of A contain
garbage initially. The array B is a std::vector which is initially empty. Use the same hash function
h(x) = x. If A[x] contains i and B[i] contains x, it means that x exists in the hash table. If A[x]
contains i but B[i] does not contain x or i is out of the range of B, it means that x does not exist in
the hash table.
*/
bool insert_hash(int x) {
if (x >= n) {//sees if x is within the range of A
} else {
if (*A[x] > bsize){//sees if i is within the range of B
} else {
if (B[*A[x]] == x) {//sees if B[i] contains x
return false;
}
}
}
B.push_back(x);//adds key x to B
bsize++;
*A[x] = bsize;//store location at A
return true;
//The new key x should be pushed at the back of B and its location is stored at A[x]. This function
//should return false if x already exists in the hash table, and returns true otherwise.
}
bool member_hash(int x) {
//The function returns true if x exists in the hash table, and returns false otherwise.
if (x <= n) {//sees if x is within the range of A
if (*A[x] > bsize){//sees if i is within the range of B
if (B[*A[x]] == x) {//sees if B[i] is x
return true;
}
}
}
return false;
}
bool delete_hash(int x) {
//This function First checks whether x exists in the hash table: If no, then it returns false. Otherwise,
//it stores -1 at the cell of B that contains x and then returns true.
if (!member_hash(x)) {
return false;
} else {
B[*A[x]] = -1;
return true;
}
}
};
int main() {
HashTable a(20);
a.insert_hash(5);
a.insert_hash(4);
a.insert_hash(2);
a.insert_hash(2);
a.insert_hash(11);
a.insert_hash(510);
a.member_hash(11);
a.delete_hash(11);
a.member_hash(11);
return 0;
}
我在 DevC++ 和 Code::Blocks 中都很好地编译了代码,但是当我尝试运行此代码时,它最终没有响应,当我在 CodePad 上运行它时,我收到消息 Segmentation Fault。 编辑:更具体地说,它说“分段错误(核心转储)” 编辑 2:分段错误似乎从 main 中的第一个 insert_hash 开始,在条件语句 (B[*A[x]] == x) 有关如何解决此问题的任何想法? 编辑 3:B[*A[x]] == x,从 member_hash 开始,似乎是因为 B 是空的。但是,我很困惑 *A[x] 中的垃圾值如何达到这个条件,因为我有其他条件 (*A[x]
【问题讨论】:
-
这段代码看起来像是尝试成为O(1) array initialization trick 的实现,但失败得很惨。这就是你想要做的吗?
-
我正在实现一个哈希表,它使用除 A 之外的另一个必需的数组 B 作为分配的一部分。是的,我正在尝试 O(1) 技巧。但是是什么导致了段错误?
-
我对@987654323@ 感到困惑。
A被声明为*A[1]。我不认为这些是兼容的。你想要 *(A+x) 吗? -
@KeithSmith,不,它给出了错误:当我尝试这样做时,ISO C++ 禁止指针和整数之间的比较
-
为什么不将
A声明为int *A,然后用普通的A替换所有其他*A?对我来说更具可读性...
标签: c++ segmentation-fault hashtable