Iterator library in C++ STL
In this article, we will learn about the Iterator library in C++ STL. Iterators are just like pointers, with the help of which we can access and traverse our data. We can also modify our data using iterators. Iterators work with addresses instead of the indexes. The standard template library in c++ provides us with many inbuilt functions and containers(to store the data). Pointers are helpful when we have to work with data while using the containers and the algorithms provided in the standard template library.
The basic syntax of an iterator is:
Template<data type> :: iteartor T; //Here template is the type of container we are using. //T is the name we want to give to the iterator //Example vector<int> :: iterator it //we have created an iterator object which will point to //the address of the elements of the vector.
A total of 5 types of iterators are available in c++ which follow a hierarchy in terms of their functionality:
The first level of the hierarchy consists of two types of iterators i.e the input iterator and the output iterator. These both have very limited functionality and are completely opposite in their functioning. We can not save this type of iterators and can only use them in the forward direction in a sequential manner.
- INPUT ITERATOR: This is a read-only iterator and hence can only be used to access the elements and not to assign the values. For example, the std:: find function uses the input iterator.
- OUTPUT ITERATOR: This is a write-only iterator and hence can only be used to assign values and not to access value. For example, the std:: copy function uses the output iterator.
The next level is occupied by the forward iterators which have the functionality of both, the input and the output iterators. We can use them only in forwards direction that too in a sequential manner. An example of such type of iterator is the std:: search function.
At the third level, we have the bidirectional iterators which have all the functionalities of input, output, and forward iterators. In addition, we can use this type of iterators in both directions in a sequential manner. Example: std:: reverse.
The topmost level is occupied by the random-access iterators which are capable of reading and writing the elements randomly in both the directions. They have maximum functionality possible. Example: std:: sort.
Also, containers present in the STL are not compatible with all the iterators mentioned above. Therefore, we also need to study compatibility. Below is the list of the type of iterators compatible with the containers present in the standard template library.