In this C++ tutorial, you will learn how to iterate over the elements of a vector using While loop, with example program.
Iterate over elements of vector using While loop in C++
To iterate over the elements of a vector using While Loop, start at zero index and increment the index by one during each iteration. During the iteration, access the element using index.
Example
In the following C++ program, we define a vector, and iterate over its elements using While loop.
main.cpp
#include <iostream> #include <vector> using namespace std; int main() { vector<string> arr{ "apple", "banana", "cherry" }; int index = 0; while ( index < arr.size() ) { string element = arr.at(index); cout << element << endl; index++; } }
Output
apple banana cherry
Conclusion
In this C++ Tutorial, we learned how to iterate over elements of a vector using While Loop.