c – 与std :: vector的一个小问题,并在循环时更改集合

前端之家收集整理的这篇文章主要介绍了c – 与std :: vector的一个小问题,并在循环时更改集合前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
该循环在运行时更改迭代器:
  1. std::vector<int> c;
  2. c.push_back(1);
  3. c.push_back(2);
  4.  
  5. std::vector<int>::iterator iter = c.begin();
  6. std::vector<int>::iterator endIter = c.end();
  7.  
  8. while( iter != endIter )
  9. {
  10. std::cout << (*iter) << std::endl;
  11. iter = c.erase(iter);
  12. }

它不工作,因为:

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开始实施了.为什么使用它是有益的?

解决方法

只是不缓存将无效的结束迭代器:
  1. while( iter != c.end() )
  2. {
  3. std::cout << (*iter) << std::endl;
  4. iter = c.erase(iter);
  5. }

或打印后清除矢量:

  1. for(const auto& i : c) {
  2. std::cout << i << std::endl;
  3. }
  4. c.clear();

猜你在找的C&C++相关文章