c++ - "vector"中的这段代码是什么意思? (C++)

标签 c++ vector iterator assertions

我创建了一个程序,它使用 vector.h #include 和迭代器等...但是当我运行该程序时,在某些情况下(我仍在尝试弄清楚它们是什么)我得到一个断言错误,将我指向 vector.h 的第 98 行。我去了 vector.h 的第 98 行,得到了这个:

 #if _HAS_ITERATOR_DEBUGGING
        if (this->_Mycont == 0
            || _Myptr < ((_Myvec *)this->_Mycont)->_Myfirst
            || ((_Myvec *)this->_Mycont)->_Mylast <= _Myptr)
            {
            _DEBUG_ERROR("vector iterator not dereferencable");
            _SCL_SECURE_OUT_OF_RANGE;
            }

有人可以告诉我这意味着什么以及我的程序中是什么导致了这个断言吗?

注意:记录在案的第 98 行是以“_DEBUG_ERROR("vect..."

注意:这是我认为触发了错误的程序中的代码,不过我不完全确定。

代码:

for(aI = antiviral_data.begin(); aI < antiviral_data.end();)
    {
        for(vI = viral_data.begin(); vI < viral_data.end();)
        {
            if((*aI)->x == (*vI)->x && (*aI)->y == (*vI)->y)
            {
                vI = viral_data.erase(vI);
                aI = antiviral_data.erase(aI);
            }
            else
            {
                vI++;
            }
        }
        if((*aI)->x >= maxx || (*aI)->x < 0 || (*aI)->y >= maxy || (*aI)->y < 0)
        {
            aI = antiviral_data.erase(aI);
        }
        else
        {
            aI++;
        }
    }

最佳答案

运行时检测到您正在取消引用 begin() 之前或 end() 之后的迭代器。

想象一下,如果您在第 7 行删除 antiviral_data vector 中的最后一项:

aI = antiviral_data.erase(aI);

aI 设置为 antiviral_data.end(),当您在第 14 行取消引用它时:

if((*aI)->x >= maxx ...

还有第 5 行:

if((*aI)->x == (*vI)->x

您正在解除对越界迭代器的引用。

解决方法是在删除调用后检查 aI != antiviral_data.end() 以确保在继续使用之前没有到达 vector 的末尾。

关于c++ - "vector"中的这段代码是什么意思? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/866776/

相关文章:

c++ - 从给定 vector 的 block 中生成新 vector

iterator - 前向和当前迭代器

c# - Queue 上的 IEnumerable 迭代器是否应该使项目出列

c++ - 迭代器和整数的减法

c++ - 线程 for 循环达到了不应该达到的值

c++ - 在 std::map 中插入一个 boost::unique_ptr

c++ - 为 vector 的 vector 分配内存

c++ - Windows 到 Linux 移植 : how to replace __stdcall?

c++ - event_base* 与 unique_ptr<event_base>

matlab - 在具有重复元素的有序向量中插入缺失的数字