【发布时间】:2011-12-26 16:27:55
【问题描述】:
我正在实现一个哈希表来帮助存储和检索应用程序的属性。目前,它大部分都在工作,除非我尝试检索一个不存在的值。我的代码应该返回一个空字符串,而不是它崩溃。这是相关的代码。数组是动态分配的。
struct Property {
Property* next;
std::string key;
std::string value;
Property() {
key = "";
value = "";
next=NULL;
}
};
Property* properties;
int propSize;
std::string Properties::getProperty(std::string key) {
Property *ptr = &properties[hashcode(key)%propSize];
if (properties[hashcode(key)%propSize].key == "") {
return "";
}
else {
while((ptr->key != key) && (ptr->next != NULL))
ptr = ptr->next;
if (ptr->key != key)
return "";
else
return ptr->value;
}
}
【问题讨论】:
-
-1: 你试过调试这个吗?你发现了什么?
-
C++ 已经在
<unordered_map>(或<tr1/unordered_map>,或<boost/unordered_map.hpp>,或<ext/hash_map>)中附带了一个专业设计的哈希表。如果目的不是学习如何编写哈希表,为什么还要自己动手呢? -
我尝试调试它,但一无所获。整个事情就在while循环中停止了。 1. 我不知道 unordered_map 2. 我需要能够浏览并保存地图中的所有条目。
标签: c++ pointers struct hashtable