To create a two-dimensional vector in C++, you can use a vector of vectors.
In this example,
matrix
as a vector of vectors, where each inner vector represents a row of the two-dimensional vector.matrix
with numeric vectors using the push_back
method.#include <iostream>
#include <vector>
int main() {
// Step 1: Create a numeric two-dimensional vector
std::vector<std::vector<int>> matrix;
matrix.push_back({1, 2, 3});
matrix.push_back({4, 5, 6});
matrix.push_back({7, 8, 9});
// Step 2: Print the two-dimensional vector
std::cout << "[";
for (const auto& row : matrix) {
std::cout << "[";
for (int num : row) {
std::cout << num << ", ";
}
std::cout << "], ";
}
std::cout << "]";
return 0;
}
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In this example,
matrix
as a vector of vectors, where each inner vector represents a row of the two-dimensional vector.matrix
with string vectors using the push_back
method.#include <iostream>
#include <vector>
#include <string>
int main() {
// Step 1: Create a string two-dimensional vector
std::vector<std::vector<std::string>> matrix;
matrix.push_back({"a", "b", "c"});
matrix.push_back({"d", "e", "f"});
matrix.push_back({"g", "h", "i"});
// Step 2: Print the two-dimensional vector
std::cout << "[";
for (const auto& row : matrix) {
std::cout << "[";
for (const std::string& str : row) {
std::cout << str << ", ";
}
std::cout << "], ";
}
std::cout << "]";
return 0;
}
[[a, b, c], [d, e, f], [g, h, i]]
In this tutorial, we learned How to create a Two Dimensional Vector in C++ language with well detailed examples.