【发布时间】:2011-12-02 02:56:00
【问题描述】:
#define TABLE_SIZE 100489 // must be a power of 2
typedef map<string,int> MAP_TYPE;
typedef pair<string, int> PAIR_TYPE;
class HashTable
{
public: //public functions
HashTable();
~HashTable();
int find(string);
bool insert(string, int);
private:
int hash( const char* );
vector< MAP_TYPE > v;
};
//HashTable constructor
HashTable::HashTable()
{
vector< MAP_TYPE > v; //initialize vector of maps
v.reserve(TABLE_SIZE); //reserve table size
MAP_TYPE m;
for (int i = 0; i < TABLE_SIZE; ++i) //fill vector with empty maps
v.push_back(m);
cout << v.size();
}
int HashTable::find(string key)
{
cout << "in find" << '\n';
//String to const char* for hash function
const char *c = key.c_str();
//find bucket where key is located
int hashValue = HashTable::hash(c);
cout << hashValue << '\n';
string s = key;
cout << v.size(); //Prints 0 but should be TABLE_SIZE
//look for key in map in bucket
MAP_TYPE::const_iterator iter = v[hashValue].find(s);
if ( iter != v[hashValue].end()) //check if find exists
return iter->second; //return value of key
else
return -1; //arbitrary value signifying failure to find key
}
int main()
{
HashTable my_hash;
string s = "hi";
int z = my_hash.find(s);
cout << z; //should return -1
return 0;
}
我正在测试我的哈希表的查找函数,但它返回了分段错误。即使我在查找函数中构造了具有正确大小的向量 v,但大小现在为 0?我不认为它访问的是同一个变量。哈希函数很好。怎么了?
【问题讨论】:
-
100489 != 2 的幂
-
@Mysticial 这就是 cmets 做出错误断言声明的原因。
-
哎呀!是的,但这没关系......哈希在向量的大小范围内。 find 中的 v.size() 不应该给我 0 吗?
-
hash的定义在哪里?
标签: c++ class variables segmentation-fault