Random Access Iterators in C++
Last Updated :
07 Jan, 2022
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 being:
Random-access iterators are iterators that can be used to access elements at an arbitrary offset position relative to the element they point to, offering the same functionality as pointers. Random-access iterators are the most complete iterators in terms of functionality. All pointer types are also valid random-access iterators.
It is to be noted that containers like vector, deque support random-access iterators. This means that if we declare normal iterators for them, and then those will be random-access iterators, just like in the case of list, map, multimap, set and multiset they are bidirectional iterators.
Also, note that Iterator algorithms do not depend on the container type. As the iterators provide common usage for all of them, the internal structure of a container does not matter.

So, from the above hierarchy, it can be said that random-access iterators are the strongest of all iterator types.
Salient Features:
1) Usability: Random-access iterators can be used in multi-pass algorithms, i.e., an algorithm which involves processing the container several times in various passes.
2) Equality/Inequality Comparison: A Random-access iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.
So, the following two expressions are valid if A and B are Random-access iterators:
A == B // Checking for equality
A != B // Checking for inequality
3) Dereferencing: A random-access iterator can be dereferenced both as an rvalue as well as an lvalue.
CPP
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1 = { 10, 20, 30, 40, 50 };
vector<int>::iterator i1;
for (i1 = v1.begin(); i1 != v1.end(); ++i1) {
*i1 = 7;
}
for (i1 = v1.begin(); i1 != v1.end(); ++i1) {
cout << (*i1) << " ";
}
return 0;
}
|
So, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is a random Access iterator.
4) Incrementable: A Random-access iterator can be incremented, so that it refers to the next element in the sequence, using operator ++(), as seen in the previous code, where i1 was incremented in the for loop.
So, the following two expressions are valid if A is a random-access iterator:
A++ // Using post increment operator
++A // Using pre increment operator
5) Decrementable: Just like we can use operator ++() with Random-access iterators for incrementing them, we can also decrement them.
CPP
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1 = { 1, 2, 3, 4, 5 };
vector<int>::iterator i1;
for (i1 = v1.end() - 1; i1 != v1.begin() - 1; --i1) {
cout << (*i1) << " ";
}
return 0;
}
|
Since, we are starting from the end of the vector and then moving towards the beginning by decrementing the pointer, which shows that the decrement operator can be used with such iterators.
6) Relational Operators: Although, Bidirectional iterators cannot be used with relational operators like =, random-access iterators being higher in hierarchy support all these relational operators.
If A and B are Random-access iterators, then
A == B // Allowed
A <= B // Allowed
7) Arithmetic Operators: Similar to relational operators, they also can be used with arithmetic operators like +, – and so on. This means that Random-access iterators can move in both the direction and that too randomly.
If A and B are Random-access iterators, then
A + 1 // Allowed
B - 2 // Allowed
CPP
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1 = { 1, 2, 3, 4, 5 };
vector<int>::iterator i1;
vector<int>::iterator i2;
i1 = v1.begin();
i2 = v1.end();
if (i1 < i2) {
cout << "Yes";
}
int count = i2 - i1;
cout << "\ncount = " << count;
return 0;
}
|
Here, since i1 is pointing to beginning and i2 is pointing to end, so i2 will be greater than i1 and also a difference between them will be the total distance between them.
8) Use of offset dereference operator ([ ]): Random-access iterators support offset dereference operator ([ ]), which is used for random-access.
If A is a Random-access iterator, then
A[3] // Allowed
CPP
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1 = { 1, 2, 3, 4, 5 };
int i;
for (i = 0; i < 5; ++i) {
cout << v1[i] << " ";
}
return 0;
}
|
9) Swappable: The value pointed to by these iterators can be exchanged or swapped.
Practical implementation: After understanding its features, it is very important to learn about its practical implementation as well. As told earlier, Random-access iterators can be used for all purposes and in every scenario. The following STL algorithm shows one of its practical implementations:
std::random_shuffle: As we know this algorithm is used to randomly shuffle all the elements present in a container. So, let us look at its internal working (Do not go into detail just look where random-access iterators can be used):
// Definition of std::random_shuffle()
template void random_shuffle(RandomAccessIterator first,
RandomAccessIterator last,
RandomNumberGenerator& gen)
{
iterator_traits::difference_type i, n;
n = (last - first);
for (i = n - 1; i > 0; --i) {
swap(first[i], first[gen(i + 1)]);
}
}
Here, we can see that we have made use of Random-access iterators, as there is no other type of iterator that supports arithmetic operators, that is why we have used it.
In fact, if you are thinking of uses of random-access iterators, then you can use random-access iterator in place of any other type of iterator since it is the strongest and the best type of iterator available in the C++ Standard library.
Similar Reads
C++ Standard Template Library (STL)
The C++ Standard Template Library (STL) is a set of template classes and functions that provides the implementation of common data structures and algorithms such as lists, stacks, arrays, sorting, searching, etc. It also provides the iterators and functors which makes it easier to work with algorith
9 min read
Containers in C++ STL (Standard Template Library)
A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them,
2 min read
STL Containers
STD::array in C++
The array is a collection of homogeneous objects and this array container is defined for constant size arrays or (static size). This container wraps around fixed-size arrays and the information of its size are not lost when declared to a pointer. In order to utilize arrays, we need to include the ar
5 min read
Vector in C++ STL
In C++, vector is a dynamic array with the ability to resize itself automatically when an element is inserted or deleted. It is the part Standard Template Library (STL) and provide various useful functions for data manipulation. Let's take a look a simple example to demonstrate the use of vector con
9 min read
List in C++ Standard Template Library (STL)
Lists are sequence containers that allow non-contiguous memory allocation. As compared to the vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick (constant time). Normally, when we say a List, we talk about a doubly linked list. For implementing
6 min read
Forward List in C++ | Set 1 (Introduction and Important Functions)
Forward list in STL implements singly linked list. Introduced from C++11, forward list are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list
9 min read
Stack 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 (top) and an element is removed from that end only. Stack uses an encapsulated object of either vector or deque (by default) or list (sequential container class) as its under
4 min read
Queue in C++ Standard Template Library (STL)
Queues are a type of container adaptors 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. Queues use an encapsulated object of deque or list (sequential container class) as its underlying container, providing a sp
3 min read
Deque in C++ Standard Template Library (STL)
Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements. Unlike vectors, contiguous storage allocation may not be guaranteed. Double Ended Queues are basi
4 min read
Set in C++ Standard Template Library (STL)
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. The std::set class is the part of C++ Standard Template Library (STL) and it is define
7 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member F
9 min read
Multiset in C++ Standard Template Library (STL)
Multisets are a type of associative containers similar to the set, with the exception that multiple elements can have the same values. Some Basic Functions associated with multiset: begin() - Returns an iterator to the first element in the multiset --> O(1)end() - Returns an iterator to the theor
6 min read
Multimap in C++ Standard Template Library (STL)
Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always. These
6 min read
Unordered Sets in C++ Standard Template Library
An unordered_set is an unordered associative container implemented using a hash table where keys are hashed into indices of a hash table so that the insertion is always randomized. All operations on the unordered_set take constant time O(1) on an average which can go up to linear time O(n) in the wo
6 min read
unordered_map in C++ STL
unordered_map is an associated container that stores elements formed by the combination of a key value and a mapped value. The key value is used to uniquely identify the element and the mapped value is the content associated with the key. Both key and value can be of any type predefined or user-defi
7 min read
C++ unordered_multiset
The unordered_multiset in C++ STL is an unordered associative container that works similarly to an unordered_set. The only difference is that we can store multiple copies of the same key in this container. It is also implemented using a hash table so the time complexity of the operations is O(1) on
7 min read
unordered_multimap and its application
Allows Duplicates: We have discussed unordered_map in our previous post, but there is a limitation, we can not store duplicates in unordered_map, that is if we have a key-value pair already in our unordered_multimap and another pair is inserted, then both will be there whereas in case of unordered_m
7 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 u
6 min read
STL Iterators
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 t
6 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 it
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 t
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 ar
7 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
6 min read
Iterators in C++ STL
An iterator in C++ is a pointer-like object that points to an element of the STL container. They are generally used to loop through the contents of the STL container in C++. The main advantage of STL iterators is that they make the STL algorithms independent of the type of container used. We can jus
11 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all < algorithm > library functions : Refer here.Some of the most used algorithms on
7 min read
STL Algorithms
sort() in C++ STL
In C++, sort() is a built-in function used to sort the given range in desired order. It provides a simple and efficient way to sort the data in C++ but it only works on data structures that provide random access to its elements such as vectors and arrays. Let's take a look at an example: [GFGTABS] C
4 min read
Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backward()
Various varieties of copy() exist in C++ STL that allows to perform the copy operations in different manners, all of them having their own use. These all are defined in header <algorithm>. This article introduces everyone to these functions for usage in day-to-day programming. 1. copy(strt_ite
5 min read
max_element in C++ STL
The std::max_element() in C++ is an STL algorithm that is used to find the maximum element in the given range. It is defined inside the <algorithm> header file. In this article, we will learn how to find the maximum element in the range using std::max_element() in C++. Example: [GFGTABS] C++ /
4 min read
find() in C++ STL
In C++, the find() is a built-in function used to find the first occurrence of an element in the given range. It works with any container that supports iterators, such as arrays, vectors, lists, and more. In this article, we will learn about find() function in C++. Letâs take a look at an example th
3 min read
for_each loop in C++
Apart from the generic looping techniques, such as "for, while and do-while", C++ in its language also allows us to use another functionality which solves the same purpose termed "for-each" loops. This loop accepts a function which executes over each of the container elements. This loop is defined i
5 min read
Algorithm Library Functions in C++ STL
Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Fin
4 min read
Functors in C++
Please note that the title is Functors (Not Functions)!! Consider a function that takes only one argument. However, while calling this function we have a lot more information that we would like to pass to this function, but we cannot as it accepts only one parameter. What can be done? One obvious an
3 min read
C++ STL Cheat Sheet
The C++ STL Cheat Sheet provides short and concise notes on Standard Template Library (STL) in C++. Designed for programmers that want to quickly go through key STL concepts, the STL cheatsheet covers the concepts such as vectors and other containers, iterators, functors, etc., with their syntax and
15+ min read
Top C++ STL Interview Questions and Answers
The Standard Template Library (STL) is a set of C++ template classes that are used to implement widely popular algorithms and data structures such as vectors, lists, stacks, and queues. It is part of the C++ Language ISO standard. STL is a popular topic among interviewers, so it is useful for both f
15+ min read