To iterate over a two-dimensional vector in C++, you can use nested loops.
In this example,
for
loops to iterate over each element of the two-dimensional vector.#include <iostream>
#include <vector>
int main() {
// Step 1: Iterate over a numeric two-dimensional vector
std::vector<std::vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Step 2: Nested loops to print each element
for (const auto& row : matrix) {
for (int num : row) {
std::cout << num << " ";
}
}
return 0;
}
1 2 3 4 5 6 7 8 9
In this example,
for
loops to iterate over each element of the two-dimensional vector.#include <iostream>
#include <vector>
#include <string>
int main() {
// Step 1: Iterate over a string two-dimensional vector
std::vector<std::vector<std::string>> matrix = { {"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"} };
// Step 2: Nested loops to print each element
for (const auto& row : matrix) {
for (const std::string& str : row) {
std::cout << str << " ";
}
}
return 0;
}
a b c d e f g h i
In this tutorial, we learned How to Iterate over a Two Dimensional Vector in C++ language with well detailed examples.