【问题标题】:using an iterator of a map<char,strring> to return a pointer map<char,strring>*使用 map<char,string> 的迭代器返回指针 map<char,string>*
【发布时间】:2020-05-21 13:10:47
【问题描述】:

我正在完成一项大学作业,因此我的问题很迂腐。

任务是实现一个大小为 26 的哈希表。哈希函数只是单词 {hash(apple) = e, hash(car) = r} 的最后一个字母。我选择使用map&lt;char, string&gt; 字符来表示字母表中的每个字母(散列)和字符串来存储输入的单词(键)。

我想搜索地图并返回一个指向需要添加新键的位置的指针。我正在使用的搜索方面是我遇到问题的指针。任何帮助将不胜感激。

map<char,string>* search(map<char,string>* hashTable, string key, char hashVal){

    map<char,string>::iterator it;
    for(it = hashTable->begin(); it != hashTable->end(); ++it){
        if(I want to return this address of hashTable){
            return &it->hashTable || something to that effect 
        }
    }
)

我想这样做的原因是在 add() 或 remove() 中实现以下用例。

void remove||add(map<char,string>* hashTable, string key){
    map<char, string>* temp = search(hashTable, key, hashVal);
    temp->second == NULL||key;
}

注意: 我知道地图库具有 at() 和 find() 之类的功能,但是使用它们并不能证明我对哈希表的理解。这是我所指的 2020 年大学数据结构作业的迂腐性质。

ps。如果您认为有更好的库可以作为我的哈希表的基础,请告诉我。可能是链表?

【问题讨论】:

  • 为什么不返回迭代器?另外,您是否需要多映射或映射到字符串集合
  • 另外,如果你事先知道大小,那么你最好只使用 std::vector 甚至 std::array 来减少间接性
  • 我会考虑使用矢量,我对它们更熟悉。最初我试图返回迭代器,但似乎不起作用并且感觉很尴尬,

标签: c++ c++11 pointers data-structures


【解决方案1】:

好的,所以我认为您的攻击方式是错误的。 std::map 已经是一个成熟的、类似哈希表的容器(畏缩,是的,我知道它不是真的,不要伤害我!)。使用它很可能会导致您从本练习中应该学到的东西误入歧途。

std::vector 是你的朋友。如果您准备好 ASCII 表,您应该能够制定一个好的散列函数:hash(val) -&gt; Index

这个例子可能会让你觉得很迂腐,但它会让哈希表的所有属性都非常明显(就像在你的脸上一样明显)。

啊,回答你的问题:std::next 有一个很好的重载来获取指向元素的指针/迭代器。

编辑附录:

(提示) 哈希表的杀手级功能在使用链表时可能会丢失......

【讨论】:

  • 搞笑的是std::unordered_map其实是用单链表实现的。在这种情况下,哈希表只包含指向列表节点的指针。
猜你喜欢
  • 2013-12-18
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 2012-02-16
  • 2023-03-15
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多