How to Traverse a Vector using for_each Loop in C++?
Last Updated :
18 Mar, 2024
In C++, vectors are dynamic containers that can change their size automatically during the insertion and deletion of elements. In this article, we will learn how we can use a for_each loop to traverse elements of a vector in C++.
Example
Input:
myVector = {1,2,3,4,5}
Output:
// Squared each element of vector and traversal.
myVector ={1,4,9,16,25}
Traverse a Vector using for_each Loop in C++
The for_each loop allows the users to iterate over the elements of the vector and apply a function to each element of the vector. We can use this loop to traverse the vector by using a function that prints the given value. We can also do any other operation that can be defined inside the
Syntax
for_each(begin, end, func)
where,
- begin: Iterator that denotes the the beginning of vector elements.
- end: Iterator that denotes the the ending of vector elements.
- funct: Name of the function to apply on each element of the vector. This function should take a single argument of container element type.
C++ Program to Traverse a Vector using for_each Loop
In the following example, we will learn how we can square each element of the vector using the for_each loop in C++.
C++
// C++ program to illustrate how we can use a for_each loop
// to traverse elements of a vector
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// declare the function you want to apply on each element of
// vector
void print(int& num) { cout << num << " "; }
void square(int& num) { num *= num; }
int main()
{
// Initialize a vector
vector<int> myVector = { 1, 2, 3, 4, 5 };
cout << "Vector Before: ";
// Traverse the element using for_each loop
for_each(myVector.begin(), myVector.end(), print);
cout << endl;
// square each element
for_each(myVector.begin(), myVector.end(), square);
cout << "Vector After: ";
// Traverse the element using for_each loop
for_each(myVector.begin(), myVector.end(), print);
cout << endl;
return 0;
}
OutputVector Before: 1 2 3 4 5
Vector After: 1 4 9 16 25
Time Complexity: O(N) where N is the total number of elements in the vector.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...