iterate const vector
#include <iostream>
#include <vector>
int main() {
const std::vector<int> numbers = {1, 2, 3, 4, 5};
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
Explanation:
Include Necessary Headers: The
#include
directives bring in the required header files (iostream
andvector
) for input/output operations and vector usage.Main Function: The
main()
function serves as the entry point for the program.Create a Constant Vector:
const std::vector<int> numbers = {1, 2, 3, 4, 5};
initializes a constant vector namednumbers
with integers 1 through 5.Iterating Through the Vector: The
for
loop initiates an iterator (it
) at the beginning of thenumbers
vector (numbers.begin()
) and continues until it reaches the end (numbers.end()
). During each iteration, it prints the value pointed to by the iterator (*it
) usingstd::cout
.Output: The program prints each element of the vector separated by a space, displaying
1 2 3 4 5
.