Menu
Coddy logo textTech

Output Iterators

Lesson 15 of 23 in Coddy's C++ - Standard Template Library course.

Output Iterator is an iterator used to modify the value in the container. They are the exact opposite of input iterators and they perform the opposite function. They are used to assign values in a sequence, but can't be used to access those values. 

As we can see, the forward iterator, bidirectional iterator and random access iterator are all valid output iterators.


So, we will learn about the features on an Output Iterator.


  • Equality/Inequality operator
    Unlike the Input iterators, the output iterator cannot be compared for equality with each other. So comparing them using the == and != operator will result into an error.
A == B // Wrong
A != B // Wrong

  • Dereferencing
    We used dereferencing an input iterator to access the value of the element that the iterator is pointing to. With the output iterator, we use the * operator to dereference the iterator so we can assign a value to the element that the iterator is pointing to.
*A = 10 // Dereference with *
vector<int> numbers = {1, 2, 3, 4, 5};
vector<int>::iterator it;

for(it=numbers.begin(); it != numbers.end(); it++)
	*it = 10;

for(it = numbers.begin(); it != numbers.end(); it++)
	cout << *it << " ";
Output:
10 10 10 10 10

 In the above example, we looped through the vector and assigned every element with the value 10 using an output iterator.


  • Incrementable
    An output iterator can be incremented, so it will refer to the next element in the sequence after the incrementation. For that we use the ++ operator
A++ // Post increment operator
++A // Pre increment operator

  • Swappable
    Two iterators pointing two different locations can be swapped.

Limitation is that an output iterator can be used to assign a value to the value that the iterator is pointing to, but we can't access that value to, for example, store the elements' value in another variable.

*A = x; // Valid
x = *A; // Invalid
challenge icon

Challenge

Medium

Given a number N from input representing the number of elements the vector will have. In the next N lines you are given one number. Store all of the numbers inside the vector. After that, use an output iterator to assign a value to each element that will be it's value incremented by one and output the modified elements.

 

Input
5
10
20
30
40
50
Output
11 21 31 41 51

Try it yourself

#include <vector>
#include <iostream>

using namespace std;

int main()
{
    vector<int> numbers;
    vector<int>::iterator it;

    // Enter your code here

    for(it = ; it != numbers.end(); )
    {

    }

    for(it = ; ; )
    {
        cout << /* Enter here */ << " ";
    }

    return 0;
}

All lessons in C++ - Standard Template Library