加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:44:35 所属栏目:百科 来源:网络整理
导读:该循环在运行时更改迭代器: std::vectorint c;c.push_back(1);c.push_back(2);std::vectorint::iterator iter = c.begin();std::vectorint::iterator endIter = c.end();while( iter != endIter ){ std::cout (*iter) std::endl; iter = c.erase(iter);} 它
该循环在运行时更改迭代器:
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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读