The Wayback Machine - https://web.archive.org/web/20240915140622/https://www.geeksforgeeks.org/iterators-c-stl/
Open In App

Iterators in C++ STL

Last Updated : 10 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite : Introduction to Iterators
Iterators are used to point at the memory addresses of STL containers. They are primarily used in sequences of numbers, characters etc. They reduce the complexity and execution time of the program.

Operations of iterators :-

1. begin() :- This function is used to return the beginning position of the container.

2. end() :- This function is used to return the after end position of the container.




// C++ code to demonstrate the working of
// iterator, begin() and end()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
    vector<int> ar = { 1, 2, 3, 4, 5 };
      
    // Declaring iterator to a vector
    vector<int>::iterator ptr;
      
    // Displaying vector elements using begin() and end()
    cout << "The vector elements are : ";
    for (ptr = ar.begin(); ptr < ar.end(); ptr++)
        cout << *ptr << " ";
      
    return 0;    
}


Output:

The vector elements are : 1 2 3 4 5 

3. advance() :- This function is used to increment the iterator position till the specified number mentioned in its arguments.




// C++ code to demonstrate the working of
// advance()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
    vector<int> ar = { 1, 2, 3, 4, 5 };
      
    // Declaring iterator to a vector
    vector<int>::iterator ptr = ar.begin();
      
    // Using advance() to increment iterator position
    // points to 4
    advance(ptr, 3);
      
    // Displaying iterator position
    cout << "The position of iterator after advancing is : ";
    cout << *ptr << " ";
      
    return 0;
      
}


Output:

The position of iterator after advancing is : 4 

4. next() :- This function returns the new iterator that the iterator would point after advancing the positions mentioned in its arguments.

5. prev() :- This function returns the new iterator that the iterator would point after decrementing the positions mentioned in its arguments.




// C++ code to demonstrate the working of
// next() and prev() 
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
    vector<int> ar = { 1, 2, 3, 4, 5 };
      
    // Declaring iterators to a vector
    vector<int>::iterator ptr = ar.begin();
    vector<int>::iterator ftr = ar.end();
     
     
    // Using next() to return new iterator
    // points to 4
    auto it = next(ptr, 3);
      
    // Using prev() to return new iterator
    // points to 3
    auto it1 = prev(ftr, 3);
      
    // Displaying iterator position
    cout << "The position of new iterator using next() is : ";
    cout << *it << " ";
    cout << endl;
      
    // Displaying iterator position
    cout << "The position of new iterator using prev()  is : ";
    cout << *it1 << " ";
    cout << endl;
      
    return 0; 
}


Output:

The position of new iterator using next() is : 4 
The position of new iterator using prev()  is : 3 


6. inserter()
:- This function is used to insert the elements at any position in the container. It accepts 2 arguments, the container and iterator to position where the elements have to be inserted.




// C++ code to demonstrate the working of
// inserter()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
    vector<int> ar = { 1, 2, 3, 4, 5 };
    vector<int> ar1 = {10, 20, 30}; 
      
    // Declaring iterator to a vector
    vector<int>::iterator ptr = ar.begin();
     
    // Using advance to set position
    advance(ptr, 3);
      
    // copying 1 vector elements in other using inserter()
    // inserts ar1 after 3rd position in ar
    copy(ar1.begin(), ar1.end(), inserter(ar,ptr));
      
    // Displaying new vector elements
    cout << "The new vector after inserting elements is : ";
    for (int &x; : ar) 
        cout << x << " ";
      
    return 0;    
}


Output:

The new vector after inserting elements is : 1 2 3 10 20 30 4 5 

Types of Iterators :

  1. Input Iterators
  2. Output Iterators
  3. Forward Iterator
  4. Bidirectional Iterators
  5. Random-Access Iterators



Previous Article
Next Article

Similar Reads

Erase Range of Elements From List Using Iterators in C++ STL
Prerequisites:List in C++Iterators in C++ A list is a type of container which requires the same properties as a doubly linked list. We can insert elements from either side of the list, but accessing elements with an index is not possible in the list. So, removing elements from the list is not an easy task. But, we have a method to remove multiple e
2 min read
Different types of range-based for loop iterators in C++
Range-Based 'for' loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container). This is very efficient when used with the standard library container (as will be used in this article) as there will be no wrong access to memory outside the scope of the iterable. The loop will automatically star
5 min read
Random Access Iterators in C++
After going through the template definition of various STL algorithms like std::nth_element, std::sort, you must have found their template definition consisting of objects of type Random-access Iterator. So what are they and why are they used?Random-access iterators are one of the five main types of iterators present in C++ Standard Library, others
6 min read
Forward Iterators in C++
After going through the template definition of various STL algorithms like std::search, std::search_n, std::lower_bound, you must have found their template definition consisting of objects of type Forward Iterator. So what are they and why are they used ? Forward iterators are one of the five main types of iterators present in C++ Standard Library,
6 min read
Difference between Iterators and Pointers in C++ with Examples
In C++ programming, we have both pointers and iterators that are used in managing and manipulating data structures. There are many similarities between iterators and pointers in their ability to reference and dereference memory, but there are certain differences between the two. Understanding the difference is very important in C++ programming. Poi
4 min read
Introduction to Iterators in C++
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 visualized as something similar to a pointer pointing to some location and we can access the content at that particular location using them. Iterators play a critical role in conne
6 min read
Bidirectional Iterators in C++
After going through the template definition of various STL algorithms like std::reverse, std::next_permutation and std::reverse_copy you must have found their template definition consisting of objects of type Bidirectional Iterator. So what are they and why are they used ? Bidirectional iterators are one of the five main types of iterators present
7 min read
Why Use Iterators Instead of Array Indices?
In C++, both iterators and array indices are used to access and manipulate elements in a container, such as arrays, vectors, and lists. However, one common question that arises is why should we prefer using iterators over array indices in certain scenarios? In this article, we will learn the advantages of using iterators over array indices, and pro
3 min read
Output Iterators in C++
After going through the template definition of various STL algorithms like std::copy, std::move, std::transform, you must have found their template definition consisting of objects of type Output Iterator. So what are they and why are they used ? Output iterators are one of the five main types of iterators present in C++ Standard Library, others be
6 min read
Input Iterators in C++
After going through the template definition of various STL algorithms like std::find, std::equal, std::count, you must have found their template definition consisting of objects of type Input Iterator. So what are they and why are they used?Input iterators are one of the five main types of iterators present in the C++ Standard Library, others being
6 min read
Sort in C++ Standard Template Library (STL)
Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort(). This function internally uses IntroSort. In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By defa
6 min read
Rotate in C++ STL
The function is defined in header &lt;algorithm&gt;. It rotates the order of the elements in the range [first, last], in such a way that the element pointed by the middle becomes the new first element. Function Template : void rotate(ForwardIterator first, ForwardIterator middle, ForwardIterator last) first, last : Forward Iterators to the initial
3 min read
deque::at() and deque::swap() in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::at()at() function is us
4 min read
list::push_front() and list::push_back() in C++ STL
Lists are containers used in C++ to store data in a non-contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::push_front() push_front() function is used to push elements into a list from the front. The n
4 min read
list::pop_front() and list::pop_back() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::pop_front() pop_front() function is used to pop or remove elements from a list from the front
4 min read
list::front() and list::back() in C++ STL
Lists are containers used in C++ to store data in a non-contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::front() This function is used to reference the first element of the list container. This func
3 min read
list::empty() and list::size() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::empty()empty() function is used to check if the list container is empty or not. Syntax : list
3 min read
list::remove() and list::remove_if() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::remove() remove() function is used to remove all the values from the list that correspond to
3 min read
queue::empty() and queue::size() in C++ STL
Queue is a type of container adaptor that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. queue::empty() empty() function is used to check if the queue container is empty or not. SyntaxqueueName.empty()ParametersThis function does not accept any parameter.Return Val
4 min read
deque::pop_front() and deque::pop_back() in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::pop_front() pop_front()
4 min read
stack empty() and stack size() in C++ STL
Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only. stack::empty()empty() function is used to check if the stack container is empty or not. Syntax : stackname.empty()Parameters :No parameters are passed.Returns :True, if sta
3 min read
stack top() in C++ STL
Stacks are a type of container adaptors with LIFO(Last In First Out) type of work, where a new element is added at one end called the top of the stack, and an element is removed from the same end only. stack::top() top() function is used to reference the top(or the newest) element of the stack. Syntax : stackname.top() Parameters: No value is neede
2 min read
queue::front() and queue::back() in C++ STL
Queue are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. queue::front() This function is used to reference the first or the oldest element of the queue container. This function can be used to fetch the first element of a queue.Syn
3 min read
forward_list::push_front() and forward_list::pop_front() in C++ STL
Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of location of only next element while list keeps tr
4 min read
map::clear() in C++ STL
Map is dictionary like data structure. It is an associative array of (key, value) pair, where only single value is associated with each unique key. map::clear() clear() function is used to remove all the elements from the map container and thus leaving it's size 0. Syntax: map1.clear() where map1 is the name of the map. Parameters: No parameters ar
2 min read
priority_queue::empty() and priority_queue::size() in C++ STL
Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the smallest element at the top by simply passing an extr
4 min read
priority_queue::push() and priority_queue::pop() in C++ STL
Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the smallest element at the top by simply passing an extr
3 min read
priority_queue::top() in C++ STL
Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. In general, elements are arranged according to some priority. However in C++ STL, the top element is the greatest element by default. We can also make a priority queue
3 min read
vector::front() and vector::back() in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::front() This function can be used to fetch the first element of a vector container.Syntax : vectorname.front() Parameters : No value is needed to pass as
3 min read
vector::empty() and vector::size() in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::empty() The empty() function is used to check if the vector container is empty or not.Syntax : vectorname.empty() Parameters : No parameters are p
5 min read
Article Tags :
Practice Tags :