在迭代数据结构时修改数据结构 [英] Modifying a data structure while iterating over it

查看:168
本文介绍了在迭代数据结构时修改数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您向数据结构(如向量)中添加元素时会出现什么情况,而
则会迭代它。我可以不这样做吗?



我试过这个,它打破了:

  int main(){
vector< int> x = {1,2,3};

int j = 0;
for(auto it = x.begin(); it!= x.end(); ++ it){
x.push_back(j);
j ++;
cout<< j<< ..;
}
}


解决方案

迭代器其他容器有关于当迭代器是什么时候有不同的规则,这些操作修改了 std :: vector



<并且不会失效。 这是一个有详细信息的好帖子此维基条目也非常清楚地总结了这些内容。



由方式,entrypoint函数 main() 必须返回 int

  int main(){...} 


What happens when you add elements to a data structure such as a vector while iterating over it. Can I not do this?

I tried this and it breaks:

int main() {
    vector<int> x = { 1, 2, 3 };

    int j = 0;
    for (auto it = x.begin(); it != x.end(); ++it) {
        x.push_back(j);
        j++;
        cout << j << " .. ";
    }
}

解决方案

Iterators are invalidated by some operations that modify a std::vector.

Other containers have various rules about when iterators are and are not invalidated. This is a good post with details. This wiki entry also summarises them quite clearly.

By the way, the entrypoint function main() MUST return int:

int main() { ... }

这篇关于在迭代数据结构时修改数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆