简体   繁体   中英

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. 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. The name it is confusing here; it's not iterator but element, that's why std::next and std::prev don't work with it.

Executes a for loop over a range.

Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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