std :: find()返回的迭代器不可取消引用 [英] iterator returned by std::find() is not dereferenceable

查看:73
本文介绍了std :: find()返回的迭代器不可取消引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是具有链接的HashTable实现的insert()函数.为了避免在linked_list中出现重复,我先检查一下是否已经存在一个值.如果是的话,那么我只是替换现有的值,因为几乎可以在末尾看到更新值"的地方看到它.该行发出一个异常,告诉我迭代器不可取消引用.为什么不能取消引用std :: find()返回的迭代器?还有另一种方法来更新找到的值吗?

This is an insert() function of an implementation of a HashTable with chaining. In order to avoid duplications in the linked_list I ckecked if a value already exists. If it does then I just replace the existing value as it can be seen almost at the end where it comments "update value". That line issues an exception telling me that the iterator is not dereferenceable. Why can't I dereference the iterator returned by std::find()? Is there another way to update the value that was found?

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不是最终迭代器,则您会做一些不相关的事情.但是在其他情况下,迭代器it等于最终迭代器,这是不可取的.但是您取消引用了它.

If the iterator it is not the end-iterator you do some irrelevant things. But in the else case the iterator it is equal to the end-iterator, and that is not dereferencable. And yet you dereference it.

我认为条件应该相反,而是使用==.

I think the condition should be the opposite, using == instead.

这篇关于std :: find()返回的迭代器不可取消引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆