转到基于范围的 for 循环中的下一个迭代器

Nik*_*ola 3 c++ iterator for-loop c++11 for-range

对于我的项目,我需要使循环中的迭代器转到容器中的下一个项目,执行一些操作,然后再次返回到同一个迭代器并继续,但是,出于某种原因,既不advance也不next然后使用prev似乎工作。那么我怎样才能获得下一个迭代器并返回到上一个迭代器呢?

我收到以下错误消息:

no matching function for call to 'next(int&)'
no type named 'difference_type' in 'struct std::iterator_traits<int>'
Run Code Online (Sandbox Code Playgroud)

谢谢!

template<class T>
void insert_differences(T& container)
{

    for(auto it : container){
        // do some operations here
        //advance(it,1);
        it = next(it); 
        // do some operations here 
        //advance(it, -1);
        it = prev(it);
        }

}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 6

基于范围的 for 循环遍历元素。这个名字it在这里令人困惑;这不是迭代器,但元素,这就是为什么std::nextstd::prev没有用它的工作。

在一个范围内执行 for 循环。

用作更易读的等效于对一系列值(例如容器中的所有元素)进行操作的传统 for 循环。

您必须像自己一样使用迭代器编写循环

for(auto it = std::begin(container); it != std::end(container); it++){
    // do some operations here
    //advance(it,1);
    it = next(it); 
    // do some operations here 
    //advance(it, -1);
    it = prev(it);
}
Run Code Online (Sandbox Code Playgroud)