Open In App

How to Use a Range-Based for Loop with a Vector in C++?

Last Updated : 05 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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++
// C++ Program to Iterate Over Elements in a Vector Using a
// Range-Based For Loop

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    // Declare and initialize a vector
    vector<int> vec = { 10, 20, 30, 40, 50 };

    // Use a range-based for loop to iterate over elements
    // in the vector
    for (const auto& num : vec) {
        cout << num << " ";
    }

    return 0;
}

Output
10 20 30 40 50 

Time Complexity : O(N) where N is the number of elements in vector
Auxilary Space : O(1)


Next Article
Article Tags :
Practice Tags :

Similar Reads