create matrix cpp
#include <iostream>
#include <vector>
class Matrix {
private:
std::vector<std::vector<int>> mat;
public:
Matrix(int rows, int cols) {
mat.resize(rows, std::vector<int>(cols, 0));
}
void setElement(int row, int col, int value) {
if (row >= 0 && row < mat.size() && col >= 0 && col < mat[0].size()) {
mat[row][col] = value;
} else {
std::cout << "Invalid index!" << std::endl;
}
}
int getElement(int row, int col) const {
if (row >= 0 && row < mat.size() && col >= 0 && col < mat[0].size()) {
return mat[row][col];
} else {
std::cout << "Invalid index!" << std::endl;
return -1; // Return a default value to indicate error
}
}
};
This code snippet defines a C++ class named Matrix
that represents a matrix of integers. It includes private member variables and public member functions to manipulate the matrix. The class uses a std::vector
of std::vector<int>
to store the matrix elements dynamically.
Explanation of key parts:
- #include <iostream>
: Includes the input/output stream for handling input and output operations.
- #include <vector>
: Includes the vector library to utilize dynamic arrays.
- class Matrix { ... };
: Defines a class named Matrix
to encapsulate matrix operations.
- private:
: Indicates that the subsequent members (here, mat
) are private and cannot be accessed directly outside the class.
- std::vector<std::vector<int>> mat;
: Defines a 2D vector mat
to store the matrix elements.
- Matrix(int rows, int cols) { ... }
: Constructor for the Matrix
class that initializes the matrix with specified rows and columns, setting all elements to 0.
- void setElement(int row, int col, int value) { ... }
: A function to set the value of a specific element in the matrix at the given row and column.
- int getElement(int row, int col) const { ... }
: A function to retrieve the value of a specific element in the matrix at the given row and column.
The code also includes index validation in the setElement
and getElement
functions to ensure that the provided row and column values are within the matrix boundaries. If an invalid index is given, an error message is displayed, and a default value (in the case of getElement
) is returned to indicate the error.