c++ - vector::reverse_iterator 在调试模式下出错,但在发行版中没有
问题描述
我使用 reverse_iterator 查找我的向量并使用 pop_back 擦除元素。但它在调试模式下会导致一些错误。我的代码是这样的:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Student{
string name;
int score;
};
int main()
{
vector<Student> testVec;
testVec.push_back(Student{ "Lilei",50 });
testVec.push_back(Student{ "YangFeifei",80 });
testVec.push_back(Student{ "WuMing",80 });
for (auto it = testVec.rbegin(); it != testVec.rend(); ++it){
if (it == testVec.rbegin()) continue;
while (it != testVec.rbegin()) {
std::cout << &(*testVec.rbegin()) << ", ";
std::cout << &(*it) << std::endl;
testVec.pop_back();
std::cout << &(*testVec.rbegin()) << ", ";
std::cout << &(*it) << std::endl; // where error occur!
}
}
std::cout << "Hello World!\n";
}
解决方案
该文档std::vector<>::pop_back()
说:
迭代器和对最后一个元素的引用以及 end() 迭代器都无效。
因此,您的it
迭代器在您调用pop_back()
. 取消引用此迭代器的行为是未定义的,因此您的程序的行为将是不可预测的。
对于您的特定情况,在调试版本中可能会有一些额外的方法让运行时确定您犯了错误,但这些检查可能会提高性能,因此可能不会包含在发布版本中。在任何情况下,行为都无法保证。it
解决方法是调用后不使用pop_back()
。
推荐阅读
- java - org.hibernate.tool.schema.spi.CommandAcceptanceException:通过 JDBC 语句执行 DDL“如果存在组 CASCADE 则删除表”时出错
- javascript - 如何仅在按下提交按钮而不是更改搜索时更改显示
- python - python在excel中删除活动过滤器并打开分组
- sql - 仅列出在列中更改了某个值的用户
- dropbox - 无法在swift 5中显示列表并从保管箱上传文件
- python - 在 Pandas 中创建新列时将相同 ID 的多行合并为一行
- c# - 无法在 EF Core 中加载类型“Microsoft.EntityFrameworkCore.Internal.ProductInfo”错误
- c# - 我怎样才能找出这个 Channel Destruct 错误?
- dbus - 如何将映射字符串到结构的字典传递给带有busctl的d-bus方法?
- java - 将带有 MySQL 的 Java Web 应用程序部署到 Digitalocean Ubuntu 液滴中时出现问题