反复修改本身已被修改的容器的C ++惯用方式 [英] C++ idiomatic way of iterating over a container that itself is being modified

查看:50
本文介绍了反复修改本身已被修改的容器的C ++惯用方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己遍历在循环内被修改的容器X.但是在每次迭代中,都需要未修改的X:

I find myself iterating over a container X that is being modified inside the loop. But in each iteration, the unmodified X is needed:

for (int x : X) { // wrong, container X in iteration should be the "original"
    modify_X();  // X modified here
}

一种解决方案是遍历一个副本

A solution is to iterate over a copy

containerT X_copy(X);
for (int x : X_copy) {
    modify_X();   
}

for (int x : containerT {X}) {
    modify_X();   
}

是否有惯用的方法?

推荐答案

问题中的最后一个例子看起来最简单.但是,从C ++ 20开始,您也可以这样做:

The last example in your question looks the simplest. However, from C++20, you could also do this:

for (auto copy = X; int i : copy)
{
  modify_X();
}

这是演示.

请注意,在您的第一个代码段中,这不仅在逻辑上是错误的,而且在您修改要迭代的范围时,还会调用未定义的行为.

Note that in your first snippet, it's not only logically wrong, but it also invokes undefined behavior, as you are modifying a range that you're iterating over.

这篇关于反复修改本身已被修改的容器的C ++惯用方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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