To iterate over a vector with index in C++, you can use a standard for loop with an index variable ranging from 0 to the size of the vector minus one.
In this example,
num_vec
containing several numeric values.for
loop to iterate over the vector. The loop variable i
ranges from 0 to num_vec.size() - 1
, where num_vec.size()
returns the number of elements in the vector.i
and print both the index and the corresponding value to the standard output.#include <iostream>
#include <vector>
int main() {
std::vector<int> num_vec = {10, 20, 30, 40, 50};
for (size_t i = 0; i < num_vec.size(); ++i) {
std::cout << "Index: " << i << " Value: " << num_vec[i] << std::endl;
}
return 0;
}
Index: 0 Value: 10 Index: 1 Value: 20 Index: 2 Value: 30 Index: 3 Value: 40 Index: 4 Value: 50
In this example,
str_vec
containing several strings.for
loop to iterate over the vector. The loop variable i
ranges from 0 to str_vec.size() - 1
, where str_vec.size()
returns the number of elements in the vector.i
and print both the index and the corresponding string to the standard output.#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> str_vec = {"apple", "banana", "cherry", "date"};
for (size_t i = 0; i < str_vec.size(); ++i) {
std::cout << "Index: " << i << " Value: " << str_vec[i] << std::endl;
}
return 0;
}
Index: 0 Value: apple Index: 1 Value: banana Index: 2 Value: cherry Index: 3 Value: date
In this tutorial, we learned How to Iterate Over a Vector with Index in C++ language with well detailed examples.