To create a vector of vectors (often representing a 2D dynamic array), you essentially create a vector where each element is itself another vector. This is commonly used in C++ for representing matrices or grids where the size can change during runtime.
Creating a Vector of Vectors in C++
Here's how you can create a vector of vectors of integers in C++:
#include <iostream>
#include <vector>
int main() {
// Declare a vector of vectors of integers.
std::vector<std::vector<int>> my2DVector;
// You can optionally initialize it with a specific size:
int rows = 3;
int cols = 4;
std::vector<std::vector<int>> initializedVector(rows, std::vector<int>(cols, 0)); // Creates a 3x4 vector initialized with 0s
// Add elements to the 2D vector (if not initialized with sizes):
std::vector<int> row1 = {1, 2, 3};
std::vector<int> row2 = {4, 5, 6};
my2DVector.push_back(row1);
my2DVector.push_back(row2);
// Accessing elements:
std::cout << "Element at row 0, column 1: " << my2DVector[0][1] << std::endl; // Output: 2
std::cout << "Element at row 1, column 2: " << my2DVector[1][2] << std::endl; // Output: 6
// Accessing elements of initialized vector:
std::cout << "Element at row 0, column 1 of initialized vector: " << initializedVector[0][1] << std::endl; // Output: 0
std::cout << "Element at row 2, column 3 of initialized vector: " << initializedVector[2][3] << std::endl; // Output: 0
return 0;
}
Explanation
-
Declaration:
std::vector<std::vector<int>> my2DVector;
declares a vector namedmy2DVector
. The outervector<>
signifies that this vector will hold other vectors. The innervector<int>
indicates that the vectors it will hold will contain integers. You can replaceint
with any other data type (e.g.,float
,std::string
, etc.) to create a vector of vectors of that type. -
Initialization (Optional):
std::vector<std::vector<int>> initializedVector(rows, std::vector<int>(cols, 0));
This initializes a 2D vector withrows
number of rows andcols
number of columns, with each element initialized to0
. This is useful when you know the dimensions of your "matrix" beforehand. -
Adding Rows: If you don't initialize with specific sizes, you can add rows to the outer vector using
push_back()
. Each row you add is itself astd::vector<int>
. -
Accessing Elements: Use the
[]
operator twice: once to access the row, and again to access the element within that row. For example,my2DVector[0][1]
accesses the element at the first row (index 0) and the second column (index 1).
Key Considerations
- Memory Management: Vectors handle memory management automatically, so you don't need to manually allocate or deallocate memory.
- Dynamic Size: Vectors can grow or shrink in size dynamically, allowing you to add or remove rows and columns as needed.
- Flexibility: This approach allows you to create "jagged" arrays, where each row can have a different number of columns (although they should typically contain same data type).