To iterate over a vector in C++, you can use a for
loop to access each element of the vector one by one.
In this example,
and
to use the std::vector
class and input/output stream.vec
and initialize it with a series of integer values using the std::vector
class.for
loop to iterate over each element of the vector. The loop variable item
will take on the value of each element in the vector, one at a time.std::cout
to print the current value of the loop variable item
.std::cout
statement sends the value of item
to the console, allowing us to see each element of the vector as it is processed.#include <vector>
#include <iostream>
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
for (int item : vec) {
std::cout << item << std::endl;
}
return 0;
}
10 20 30 40 50
In this example,
,
, and
to use the std::vector
and std::string
classes and input/output stream.vec
and initialize it with a series of string values using the std::vector
class.for
loop to iterate over each element of the vector. The loop variable item
will take on the value of each element in the vector, one at a time.std::cout
to print the current value of the loop variable item
.std::cout
statement sends the value of item
to the console, allowing us to see each element of the vector as it is processed.#include <vector>
#include <iostream>
#include <string>
int main() {
std::vector<std::string> vec = {"apple", "banana", "cherry", "date", "elderberry"};
for (const std::string& item : vec) {
std::cout << item << std::endl;
}
return 0;
}
apple banana cherry date elderberry
In this tutorial, we learned How to Iterate Over a Vector in C++ language with well detailed examples.