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++
// C++ Program to access array elements using an iterator #include <iostream> #include <vector> using namespace std;
int main()
{ // Declare and initialize a vector.
vector< int > v = { 6, 1, 5, 3, 2, 7 };
// Declare and initialize a iterator pointing at the
// beginning of the vector.
auto itr = v.begin();
// accessing element using iterator
cout << "Element at Index 4: " << *(itr + 4) << endl;
return 0;
} |
Output
Element at Index 4: 2
Time Complexity: O(1)
Space Complexity: O(1)