gpt4 book ai didi

c++ - vector 迭代器不兼容 : DEBUG

转载 作者:搜寻专家 更新时间:2023-10-31 00:37:14 24 4
gpt4 key购买 nike

为什么这段代码给我错误:Vector iterators incompatible

这段代码追溯到Rogue Wave文件tpordvec.h

    std::vector<T*> v;
const T* a // Where T is a template Class
for (std::vector<T*>::iterator p = v.begin(); p != v.end(); p++)
{
if (**p == *a)
{
T* temp = *p;
if ( v.erase(p) == v.end()) //ASSERTION ERROR HERE
return NULL;

return temp;
}
}

最佳答案

http://en.cppreference.com/w/cpp/container/vector/erase

Iterators and references to the erased elements and to the elements between them and the end of the container are invalidated. The past-the-end iterator is also invalidated.

因此,如果 vector.end()vector.erase()vector.erase() 真正删除和这样做会使迭代器在 end() 之前无效,对 operator==() 的调用将在两个不兼容的迭代器之间进行。

像这样会更好:

auto it = v.erase(p); 
if ( it == v.end())
{
return NULL;
}

关于c++ - vector 迭代器不兼容 : DEBUG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20268636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com