该循环在运行时更改迭代器:
std::vector<int> c; c.push_back(1); c.push_back(2); std::vector<int>::iterator iter = c.begin(); std::vector<int>::iterator endIter = c.end(); while( iter != endIter ) { std::cout << (*iter) << std::endl; iter = c.erase(iter); }
它不工作,因为:
Iterators and references to the erased elements and to the elements between them and the end of the container are invalidated. Past-the-end iterator is also invalidated
如何重写(不使用std :: list,并使用while循环)?
顺便说一句,我知道汽车从C11开始实施了.为什么使用它是有益的?
解决方法
只是不缓存将无效的结束迭代器:
while( iter != c.end() ) { std::cout << (*iter) << std::endl; iter = c.erase(iter); }
或打印后清除矢量:
for(const auto& i : c) { std::cout << i << std::endl; } c.clear();