在下一个循环之前访问基于 for 循环范围的下一个元素

Accessing next element in range based for loop before the next loop

本文关键字:循环 下一个 for 范围 元素 访问      更新时间:2023-10-16
如何在

下一个循环之前访问基于范围的 for 循环中的下一个元素?

我知道使用迭代方法可以执行类似 arr[++i] 的操作,但是如何在基于范围的 for 循环中实现相同的结果?

for (auto& cmd : arr) {
   steps = nextElement; //How do I get this nextElement before the next loop?
}

我知道我可能不应该使用基于范围的 for 循环,但这是为这个项目提供的要求。

如果范围具有连续的存储(例如 std::vectorstd::arraystd::basic_string或本机数组),那么你可以这样做:

for (auto& cmd : arr) {
    steps = *(&cmd + 1);
}

否则,如果没有外部变量,则无法执行。