How to Use a Range-Based for Loop with a Vector in C++?
Last Updated :
05 Feb, 2024
C++ introduced the range-based for loop as a convenient way to iterate over elements in a container. In this article, we’ll look at how to iterate over a vector using a range-based loop in C++.
Example
Input:
myVector: {1, 2, 3, 4, 5}
Output:
1 2 3 4 5
Range-Based for Loop with Vector in C++
The syntax of range-based for loop is:
for (const auto &element : container_name) {
// Code to be executed for each element
}
We can use this syntax with our vector to iterator over each element.
C++ Program to Print Vector Using Range-Based for Loop
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec = { 10, 20, 30, 40, 50 };
for ( const auto & num : vec) {
cout << num << " " ;
}
return 0;
}
|
Time Complexity : O(N) where N is the number of elements in vector
Auxilary Space : O(1)
Share your thoughts in the comments
Please Login to comment...