首页 > 解决方案 > 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";
}

标签: c++vectorstlreverse-iterator

解决方案


该文档std::vector<>::pop_back()说:

迭代器和对最后一个元素的引用以及 end() 迭代器都无效。

因此,您的it迭代器在您调用pop_back(). 取消引用此迭代器的行为是未定义的,因此您的程序的行为将是不可预测的。

对于您的特定情况,在调试版本中可能会有一些额外的方法让运行时确定您犯了错误,但这些检查可能会提高性能,因此可能不会包含在发布版本中。在任何情况下,行为都无法保证。it解决方法是调用后不使用pop_back()


推荐阅读