由 std::find() 返回的迭代器不可取消引用

iterator returned by std::find() is not dereferenceable

本文关键字:迭代器 不可取 可取消 引用 std find 返回      更新时间:2023-10-16

这是一个带有链接的HashTable实现的insert((函数。为了避免linked_list重复,如果已经存在值,我会犹豫不决。如果是这样,那么我只是替换现有值,因为它几乎可以在最后评论"更新值"的地方看到。该行发出一个异常,告诉我迭代器不可取消引用。为什么我不能取消引用 std::find(( 返回的迭代器?有没有其他方法可以更新找到的值?

virtual void insert(const K& k, const V& v) {
auto index = hashFctn(k, m_table.capacity());
if (needsToGrow() || m_table[index].m_list.size() >= m_load_factor) {
rehash();
insert(k, v);
}
else {
auto it = std::find(m_table[index].m_list.begin(), 
m_table[index].m_list.end(), v);
if (it != m_table[index].m_list.end()) { // if found add it
m_table[index].m_flag = flag::IN_USE;
m_table[index].m_key = k;
m_table[index].m_list.push_back(v);
m_nbrOfElements++;
} else {
*it = v; // update value if exists
}
}
}

你有

if (it != m_table[index].m_list.end()) { // if found add it
// Irrelevant...
} else {
*it = v; // update value if exists
}

如果迭代器it不是最终迭代器,则执行一些不相关的事情。但在 else 情况下,迭代器it等于结束迭代器,这是不可取消引用的。然而你取消引用它。

我认为条件应该是相反的,改用==