微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

它不工作,因为:

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();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐