3

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

}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Nikola
  • 133
  • 9
  • 1
    The problem is that [the range-for statement](https://en.cppreference.com/w/cpp/language/range-for) iterates over *values* in the container. The variable `it` in your case is a *value* from the container, not an iterator. And there's no way to get an iterator from a value. If you need to use actual iterators, then you should create such a loop explicitly (the "normal" `for` loop) using actual iterators. – Some programmer dude Jun 16 '20 at 06:48

1 Answers1

6

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);
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405