loop through a vector in c++
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {2, 4, 6, 8, 10};
// Loop through the vector using a for loop
for (size_t i = 0; i < numbers.size(); ++i) {
std::cout << numbers[i] << " ";
}
return 0;
}
Include Libraries: Include necessary libraries (
iostream
andvector
).Main Function: Declare the main function.
Vector Creation: Create a vector named
numbers
of integers and initialize it with values{2, 4, 6, 8, 10}
.For Loop: Start a
for
loop to iterate through the vector.size_t i = 0;
: Initialize a variablei
as an unsigned integer and set it to 0.i < numbers.size();
: Condition to check ifi
is less than the size of thenumbers
vector.++i
: Increment the value ofi
after each iteration.Access and Output: Inside the loop, access elements of the vector using
numbers[i]
and output each element followed by a space usingstd::cout
.Return: End the main function and return 0, indicating successful execution.