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

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)




Reffered: https://www.geeksforgeeks.org


C++

Related
Set of Maps in C++ Set of Maps in C++
Lambda Capture Clause in C++ Lambda Capture Clause in C++
How to Read a File Line by Line in C++? How to Read a File Line by Line in C++?
How to Remove Last Element from Vector in C++? How to Remove Last Element from Vector in C++?
How to Access Elements of Set of Maps in C++? How to Access Elements of Set of Maps in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14