Home » C++ Input Iterator

C++ Input Iterator

by Online Tutorials Library

C++ Input Iterator

  • Input Iterator is an iterator used to read the values from the container.
  • Dereferencing an input iterator allows us to retrieve the value from the container.
  • It does not alter the value of a container.
  • It is a one-way iterator.
  • It can be incremented, but cannot be decremented.
  • Operators which can be used for an input iterator are increment operator(++), decrement operator(–), dereference operator(*), not equal operator(!=) and equal operator(==).
  • An input Iterator is produced by the Istream.
  • A Forward iterator, bidirectional iterator, and random access iterator are all valid input iterators.
Property Valid Expressions
An input iterator is a copy-constructible, copy-assignable and destructible. X b(a);
b= a;
It can be compared by using a equality or inequality operator. a==b;
a!=b;
It can be dereferenced. *a;
It can be incremented. ++a;

Where ‘X’ is of input iterator type while ‘a’ and ‘b’ are the objects of an iterator type.

Features of Input iterator:

  • Equality/Inequality operator: An input iterator can be compared by using an equality or inequality operator. The two iterators are equal only when both the iterators point to the same location otherwise not. Suppose ‘A’ and ‘B’ are the two iterators:

Let’s see a simple example:

Output:

Both the iterators are not equal  

In the above example, itr and itr1 are the two iterators. Both these iterators are of vector type. The ‘itr’ is an iterator object pointing to the first position of the vector and ‘itr1’ is an iterator object pointing to the second position of the vector. Therefore, both the iterators point to the same location, so the condition itr1!=itr returns true value and prints “Both the iterators are not equal“.

  • Dereferencing an iterator: We can dereference an iterator by using a dereference operator(*). Suppose ‘A’ is an iterator:

Let’s see a simple example:

Output:

11  

In the above example, ‘it’ is an iterator object pointing to the first element of a vector ‘v’. A dereferencing an iterator *it returns the value pointed by the iterator ‘it’.

  • Swappable: The two iterators pointing two different locations can be swapped.

Let’s see a simple example:

Output:

22 11  

In the above example, ‘it’ and ‘it1’ iterators are swapped by using an object of a third iterator, i.e., temp.

Next Topic

You may also like