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

前端之家收集整理的这篇文章主要介绍了c – 与std :: vector的一个小问题,并在循环时更改集合前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
该循环在运行时更改迭代器:
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);
}@H_404_3@ 
 

它不工作,因为:

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);
}@H_404_3@ 
 

或打印后清除矢量:

for(const auto& i : c) {
    std::cout << i << std::endl;
}
c.clear();@H_404_3@
原文链接:https://www.f2er.com/c/113847.html

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