Why `it1++` works, but `it1=it1+1` does not, where it1 is iterator of list container

Viewed 299

Given a std::list iterator called it, it1++ is equivalent to it1=it1+1. So why then does it1++ work fine, but it1=it1+1 is giving an error in the below code?

Code

#include <iostream>
#include <list>

int main()
{
    std::list<int> l1{19, 2, 3, 21, 5, 19, 7, 11};
    std::list<int>::iterator it1;

    std::cout << "1st\n";
    it1 = l1.begin();
    it1++;
    it1 = it1 + 1; // This giving error
}

Output

Invalid operands to binary expression
 ('std::list<int>::iterator' (aka '_List_iterator<int>') and 'int')
1 Answers

Re: "it1++ is equivalent to it1=it1+1” -- that's not the case. It's true for built-in numeric types, but once overloaded operators come into play, there's no inherent connection between the two operators. Iterators for std::list are forward iterators; they do not have an operator+, but they do have an operator++.

Edit, elaboration:

A forward iterator let’s you move forward in a sequence. To do that, it provides two overloads of operator++, so that you can write it++ and ++it. std::forward_list provides forward iterators.

A bidirectional iterator let’s you move forward and backward in a sequence. In addition to the operations provided by forward iterators, it provides two overloads of operator--, so that you can write it-- and --it. std::list provides bidirectional iterators.

A random access iterator let’s you move to arbitrary places in the sequence. In addition to this operations provided by bidirectional iterators, it provides an overload of operator+ so that you can write it + 3. It also provides an overload of operator[] so that it[n] is equivalent to *(it + n). std::vector provides random access iterators.

Related