c++for-loopc++11iteratorfor-range

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

}

Solution

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