C++ How to iterate vector?
In C++, you can iterate over a vector using a range-based for
loop or an iterator. Here are examples of both methods:
- Range-based
for
loop:
std::vector<int> v {1, 2, 3, 4, 5}; for (int i : v) { std::cout << i << " "; }
Output:
1 2 3 4 5
In this example, we use a range-based for
loop to iterate over the elements of the vector v
. The loop variable i
takes on the value of each element in turn, and we print it to the console.
- Iterator:
std::vector<int> v {1, 2, 3, 4, 5}; for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) { std::cout << *it << " "; }
Output:
1 2 3 4 5
In this example, we use an iterator to iterate over the elements of the vector v
. We declare an iterator it
and initialize it to the beginning of the vector using the begin()
method. We then loop while the iterator is not equal to the end of the vector (end()
method), incrementing the iterator at each iteration. Inside the loop, we dereference the iterator (*it
) to get the value of the current element, and print it to the console.
Both of these methods allow you to iterate over a vector in C++. The range-based for
loop is usually more concise and easier to read, but the iterator method gives you more control over the loop and allows you to manipulate the iterator directly if necessary.