c++ loop vector iterator
Here is an example of a C++ loop using a vector iterator:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Create an iterator to iterate over the vector
std::vector<int>::iterator it;
// Loop through the vector using the iterator
for (it = numbers.begin(); it != numbers.end(); ++it) {
// Print the current element
std::cout << *it << " ";
}
return 0;
}
Explanation:
We include the necessary header files,
iostream
andvector
, that are required for using vectors and input/output operations in C++.In the
main()
function, we create a vector callednumbers
and initialize it with some values:{1, 2, 3, 4, 5}
.We declare an iterator called
it
of typestd::vector<int>::iterator
. This iterator will be used to iterate over the elements of the vectornumbers
.We use a
for
loop to iterate over the vector from the beginning (numbers.begin()
) to the end (numbers.end()
). The loop conditionit != numbers.end()
checks if the iterator has reached the end of the vector.Inside the loop, we use the dereference operator
to access the value pointed to by the iterator (
it
). In this case, we print the current element of the vector usingstd::cout
.Finally, we return
0
to indicate successful program execution.
Note: The iterator is a pointer-like object that allows us to access elements in a container, such as a vector, in a sequential manner. We can increment the iterator using the ++
operator to move to the next element.