In this C++ tutorial, you will learn how to iterate over elements of a vector using ForEach statement, with example program.
C++ For Each Element in Vector
To execute a set of statements for each element in the vector, we can use C++ For-Each statement.
Example
In the following C++ program, we define a vector, and execute a set of statements for each element in this vector.
main.cpp
#include <iostream> #include <vector> using namespace std; int main() { vector<string> arr{ "apple", "banana", "cherry" }; for ( string x: arr ) { cout << "Eat " << x << "." << endl; } }
Output
Eat apple. Eat banana. Eat cherry.
Conclusion
In this C++ Tutorial, we learned how to execute a set of statements for each element in a vector using For-Each statement.