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

the*_*cts 6 c++ loops

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

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

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

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

Ben*_*ley 8

如果范围有连续的存储(例如std::vectorstd::arraystd::basic_string或天然阵列),则可以做到这一点:

for (auto& cmd : arr) {
    steps = *(&cmd + 1);
}
Run Code Online (Sandbox Code Playgroud)

否则,如果没有外部变量,你就不能。

  • 请注意,您必须单独处理“steps”为空的情况(即,如果“cmd”是最后一个元素)。 (3认同)