iteraate through a vector
To iterate through a vector in C++, you can use a range-based for loop or a regular for loop. Here's an example using a range-based for loop:
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector = {1, 2, 3, 4, 5};
for (int element : myVector) {
std::cout << element << " ";
}
return 0;
}
Here's an explanation of each step:
We include the necessary header files,
<iostream>
and<vector>
, which provide the necessary functionalities for input/output and vectors respectively.We declare the
main
function.We create a vector called
myVector
and initialize it with some values.We use a range-based for loop to iterate through each element in the vector. The loop variable
element
takes on the value of each element inmyVector
in each iteration of the loop.Inside the loop, we print the value of
element
followed by a space.Finally, we return 0 to indicate successful program execution.
When you run this program, it will output:
1 2 3 4 5
This demonstrates how to iterate through a vector in C++ using a range-based for loop.