Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在下一个循环之前访问基于范围的for循环中的下一个元素_C++_Loops - Fatal编程技术网

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

C++ 在下一个循环之前访问基于范围的for循环中的下一个元素,c++,loops,C++,Loops,如何在下一个循环之前访问基于范围的for循环中的下一个元素 我知道使用迭代方法可以执行类似于arr[++I]的操作,但是如何在基于范围的for循环中实现相同的结果呢 for (auto& cmd : arr) { steps = nextElement; //How do I get this nextElement before the next loop? } 我知道我可能不应该使用基于范围的for循环,但这是本项目提供的要求。如果范围具有连续存储(例如std::vector

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

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

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

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

如果范围具有连续存储(例如
std::vector
std::array
std::basic_string
或本机数组),则可以执行以下操作:

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

否则,如果没有外部变量,您就无法跟踪索引。

您可能需要自己跟踪索引。您可以创建自己的类型来访问后续元素。我想可以在没有外部变量的情况下使用
std::find
。不过,如果容器中有多个容器,可能需要一些修改。这正是我要找的。谢谢请注意,您必须单独处理
steps
为空的情况(即,如果
cmd
是最后一个元素)。这会破坏所有可能的用途,取决于存储类型,并且有角盒。我们不要那样做。