问题描述
我的问题是我的代码的某些部分在 Release 模式下运行没有问题,但在 Debug 模式下出现错误。
设置: C++ 17 - Visual Studio 2019
int main()
{
//Vector containing 20 lists with length of 10 each. Every Element = 10
std::vector<std::list<int>> test(20,std::list<int>(10,10));
std::cout << test[6].front() << std::endl; //test if initialization worked
std::list<int>::iterator test_iter;
for (test_iter = test[6].begin(); test_iter != test[6].end(); test_iter++)
{
std::cout << *test_iter << std::endl;
test[6].erase(test_iter);
}
}
有人知道为什么两种模式之间存在差异以及我如何调整它,因此调试模式也能正常工作吗?
提前感谢您的帮助!
最好的问候 大卫
解决方法
问题不在于它在调试中不起作用,而是它似乎在发布中工作 - 代码在两者中同样被破坏,但库的调试版本有一些额外的错误检查代码。
错误消息有点神秘,但它想说的是您正在尝试增加一个无法递增的迭代器。
发生这种情况是因为 test[6].erase(test_iter);
使 test_iter
无效,并且在此之后使用它是未定义的。
erase
返回一个迭代器到被擦除元素之后的元素,你可以使用这个迭代器而不是递增:
for (test_iter = test[6].begin(); test_iter != test[6].end(); /* empty */)
{
std::cout << *test_iter << std::endl;
test_iter = test[6].erase(test_iter);
}