简体   繁体   English

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

[英]Go to next iterator in range-based for loop

for my project I need to make the iterators from the loop to go to the next item in the container, do some operations, and return again back to the same iterator and just continue, however, for some reason neither advance nor next and then using prev seem to work.对于我的项目,我需要使从循环到 go 的迭代器到容器中的下一个项目,执行一些操作,然后再次返回到同一个迭代器并继续,但是,由于某种原因既不advance也不next然后使用上一个prev工作。 So how could I get the next iterator and just return to prev one?那么我怎样才能获得下一个迭代器并返回到上一个迭代器呢?

I get the following error message:我收到以下错误消息:

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

Thank you!谢谢!

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);
        }

}

Range-based for loop iterates over elements.基于范围的 for 循环迭代元素。 The name it is confusing here;它的名称在it令人困惑; it's not iterator but element, that's why std::next and std::prev don't work with it.它不是迭代器而是元素,这就是为什么std::nextstd::prev不能使用它的原因。

Executes a for loop over a range.在一个范围内执行 for 循环。

Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.用作对一系列值(例如容器中的所有元素)进行操作的传统 for 循环的更易读等价物。

You have to write the loop using iterators by yourself like您必须自己使用迭代器编写循环,例如

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM