vector of vector definaion in c++
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> matrix;
// Adding elements to the matrix
std::vector<int> row1 = {1, 2, 3};
std::vector<int> row2 = {4, 5, 6};
std::vector<int> row3 = {7, 8, 9};
matrix.push_back(row1);
matrix.push_back(row2);
matrix.push_back(row3);
// Accessing elements in the matrix
std::cout << "Element at matrix[1][2]: " << matrix[1][2] << std::endl;
return 0;
}
Explanation:
- #include <iostream>
: Includes the input/output stream library to perform input and output operations.
- #include <vector>
: Includes the vector library to work with vectors.
- std::vector<std::vector<int>> matrix;
: Declares a 2D vector named matrix
that holds int
values. It's a vector of vectors, essentially representing a matrix.
- std::vector<int> row1 = {1, 2, 3};
, std::vector<int> row2 = {4, 5, 6};
, std::vector<int> row3 = {7, 8, 9};
: Creates three vectors row1
, row2
, and row3
with integer elements.
- matrix.push_back(row1);
, matrix.push_back(row2);
, matrix.push_back(row3);
: Adds row1
, row2
, and row3
as rows to the matrix
vector.
- std::cout << "Element at matrix[1][2]: " << matrix[1][2] << std::endl;
: Prints the element at row index 1 and column index 2 of the matrix
vector.