Loading....
Coupon Accepted Successfully!

 

Iterators

Iterators acts as pointers. They are used for accessing contents of container classes. They allow movement from one element to another element, and this is known as iterating. Each container type supports one kind of iterator according to the container’s necessity. The types are input, output, forward, bi-directional, and random access. The hierarchy of iterators is shown in Figure 20.3 and described in Tables 20.5 and 20.6.

125689.png

Fig.  20.3 Iterator hierarchy

Table 20.5 Operation of container classes

Iterator

Access mode

Way of action

I /O ability

Comments

Forward

Linear

Can move forward only

Can Write & read

Storable

Bi-directional

Linear

Can move Front & back

Can write & read

Storable

Random

Random

Can move Front & back

Can write & read

Storable

Input

Linear

Can move Frontward only

Can Read only

Non-storable

Output

Linear

Can move Frontward only

Can Write only

Non-storable

 

Table 20.6 Iterator status

Iterator status

Meaning

singular

The value of iterator does not dereference in any container.

Past-the-end

The iterator addresses to the object past the last object in the container.

dereferenceable

The iterator addresses the legal object in the container.

Iterators are used by the algorithms to carry out operations. Iterators are smart pointers. They are allowed to contain values that indicate one of the statuses of iterators as described in Table 20.10. Each iterator type supports all the attributes listed in Table 20.9 and shown in Figure 20.3. Iterators can be incremented, decremented, and their limits are up to the capacity of the containers. Containers have member functions that return iterators.

20.3 Write a program to transverse list using iterator.

#include<iostream>

#include<list>

using namespace std;

typedef list<int> num_list;

int main()

{

num_list num;

for (int j=0;j<=5;++j)

num.push_back(j);

for (num_list::const_iterator ls=num.begin(); ls!=num.end();++ls)

cout<<*ls<<“”;

return 0;

}

OUTPUT

0 1 2 3 4 5

 

Explanation: In the above program, num is an object of type num_list. The member function push_back() adds a number in the list. In the for loop, the statement num_list::const_iterator ls = num.begin(); declares an iterator ls and initializes with the beginning reference of the list (reference of the first element). The second statement ls! = num.end() continues the loop until the ls points to the last element of the list. The statement ++ls dereference the iterator so that successive numbers are accessed.





Test Your Skills Now!
Take a Quiz now
Reviewer Name