I use reverse_iterator to look up my vector and using pop_back to erase elements.But it causes some error in debug mode. My code is this:
#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";
}
This documentation for
std::vector<>::pop_back()says that:Therefore, your
ititerator is invalid after you calledpop_back(). The behaviour of dereferencing this iterator is undefined, so your program's behaviour will be unpredictable.For your particular case, it's possible that in debug builds there are some additional methods for the runtime to determine that you have made a mistake, but these checks may be costly for performance so may not be included in a release build. In any case, the behaviour is not guaranteed. The solution is to not use
itafter callingpop_back().