Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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')
like image 845
Abhishek Mane Avatar asked Oct 16 '21 15:10

Abhishek Mane


People also ask

Which function is used to get a move iterator from a container?

struct vec{ iterator begin() ; const_iterator begin() const; };

How does C++ iterator work?

An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualised as something similar to a pointer pointing to some location and we can access content at that particular location using them.

What are iterators used for?

The primary purpose of an iterator is to allow a user to process every element of a container while isolating the user from the internal structure of the container. This allows the container to store elements in any manner it wishes while allowing the user to treat it as if it were a simple sequence or list.


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.

like image 109
Pete Becker Avatar answered Oct 12 '22 00:10

Pete Becker