11

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')
JaMiT
  • 14,422
  • 4
  • 15
  • 31
Abhishek Mane
  • 619
  • 7
  • 20
  • 1
    @Bathsheba At a guess, some of the downvoting might be because the question started with code (I've now rectified that.), which typically is a bad sign indicating that the asker has not thought through the question. – JaMiT Oct 16 '21 at 17:22

1 Answers1

8

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.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • Can you please change `operator—` to `operator--`, I can't request an edit with that few changes. It might confuse. – thomas.st Oct 18 '21 at 05:08
  • @thomas.st -- thanks for pointing that one out. My iPad insists on making that change; I fixed it everywhere else, and missed that one. Good thing my main system isn't that smart. – Pete Becker Oct 18 '21 at 14:02