【问题标题】:C++ get property from hash table using chainingC ++使用链接从哈希表中获取属性
【发布时间】: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


【解决方案1】:

使用几个标准哈希表实现之一,例如unordered_map。您提到您“需要能够浏览并保存地图中的所有条目”;迭代地图并对元素做任何你想做的事情是微不足道的,例如使用std::copy()

【讨论】:

  • 目前,unordered_map 的所有实现都不起作用。在link 之后,我收到错误“命名空间‘std’中的‘tr1’没有命名类型。”使用 boost 的版本时,我在标题中的代码出现错误。
猜你喜欢
  • 1970-01-01
  • 2011-08-17
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-06
  • 2012-01-21
  • 1970-01-01
相关资源
最近更新 更多