How to Use Iterator with a Vector in C++?
Last Updated :
27 Feb, 2024
In C++, vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted. An iterator is a pointer-like object that can be used to access elements of a container (like an array or a vector). In this article, we will learn how to use an iterator with a vector in C++.
Iterator with a Vector in C++
We can use the iterator with a vector in the same way as we can use the pointer with arrays. The std::vector member functions std::vector::begin() and std::vector::end() return the iterator to the beginning and the end respectively.
We can then use the increment and decrement operations to move through the vector while accessing and manipulating the value of the elements.
C++ Program to Traverse Vector with Iterator
The below example demonstrates how to use an iterator with a vector for traversal.
C++
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
void printVector(vector< int >& v)
{
vector< int >::iterator myItr;
for (myItr = v.begin(); myItr != v.end(); myItr++) {
cout << *myItr << " " ;
}
cout << endl;
}
int main()
{
vector< int > v = { 1, 2, 3, 4, 5 };
printVector(v);
return 0;
}
|
Time Complexity: O(N), where N is the size of the vector.
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...