c++ - 为什么我的 vector 代码断言?到底什么是断言?

标签 c++ vector assertions

“断言”到底是什么,或者更具体地说,我如何摆脱错误。当我创建一个指向具有数据成员 int x 的类的指针 vector 时,然后执行以下操作:

for(I=antiviral_data.begin();I<antiviral_data.end();I++)
{
    if((*I)->x>maxx)
    {
        antiviral_data.erase(I);
    }
}

然后运行程序,在 x 大于 maxx 并且我使用 .erase() 之前我没有得到任何错误,此时我得到了这个错误:

Debug Assertion Failed!

Program: ...My Documents\O.exe File: ...include\vector Line: 116

Expression: ("this->_Has_container()",0)

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)

[Abort][Retry][Ignore]

此外,如果我尝试使用 cout:

cout<<(*antiviral_data.begin())->x<<endl;

我收到这个错误:

Debug Assertion Failed!

Program: ...My Documents\O.exe File: ...include\vector Line: 98

Expression: vector iterator not deferencable

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)

[Abort][Retry][Ignore]

有人能告诉我为什么我不能使用 vector 中的任何数据,以及如何解决这个问题吗?

另外:antiviral_data 是一个指针 vector ,只有一个元素:

antiviral_data.push_back(new aX1(player.x,player.y,'>'));

如果有帮助。

最佳答案

您得到断言的最可能原因是您在删除后递增 I。试试这个:

for(I=antiviral_data.begin();I!=antiviral_data.end();)
{
    if((*I)->x>maxx) I=antiviral_data.erase(I); else ++I;
}

另见 http://www.cppreference.com/wiki/stl/vector/erase ,在该页面上搜索无效迭代器

关于c++ - 为什么我的 vector 代码断言?到底什么是断言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/817429/

相关文章:

c++ - 运行时错误(SIGKILL)

c++ - 静态数据成员和全局变量的区别

C++检查 vector 中一行中有多少个相同元素

ios - iOS从PDF提取矢量图形

php - 谁能引导我找到正则表达式的 DEFINE 断言文档?

java - TestNG AssertEquals double - 一个双倍的好数字?

c++ - 具有新放置的右值引用(与 std::vector.push_back 类似的功能)

c++ - 迭代器的值

c++ - 使用 C++ vector 而不是 C 数组的性能损失

c++ - 如何否定 gtest assert 或 expect that 中的匹配器?