How to Use Iterator with a Vector in C++?
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++
// C++ Program to show how use an Iterator to traverse a vector #include <iostream> #include <iterator> #include <vector> using namespace std; // Print vector function using iterators void printVector(vector< int >& v) { // Create iterator of vector<int> type vector< int >::iterator myItr; // Initialize iterator and begine traversal for (myItr = v.begin(); myItr != v.end(); myItr++) { cout << *myItr << " " ; } cout << endl; } int main() { // Create and initialize a vector vector< int > v = { 1, 2, 3, 4, 5 }; // Print vector printVector(v); return 0; } |
1 2 3 4 5
Time Complexity: O(N), where N is the size of the vector.
Space Complexity: O(1)