How to Access Vector Element Using Iterator in C++?
Last Updated :
06 Feb, 2024
In C++, vectors are container that works like a dynamic array. STL provides iterators for the traversal of these containers. In this article, we will learn how to access an element in a vector using an iterator in C++.
Example
Input:
myVector = {1, 5, 8, 1, 3, 4}
Output:
myVector value at index 5 using iterator: 4
Access Element in a Vector Using Iterator in C++
Iterators work like a pointer to the elements. We first get the iterator to the beginning (or first element) of the vector using the std::vector::begin() function. Then we add the index of the element that we want to access and dereference it like a pointer using the dereferencing operator.
C++ Program To Access Vector Element Using Iterator in C++
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > v = { 6, 1, 5, 3, 2, 7 };
auto itr = v.begin();
cout << "Element at Index 4: " << *(itr + 4) << endl;
return 0;
}
|
Output
Element at Index 4: 2
Time Complexity: O(1)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...