Answer the question
In order to leave comments, you need to log in
How to set the dimensions of a matrix (vector of vectors) in C++ after it has been created?
The class has a matrix , it is required, based on two arguments in the constructor, to set the dimensions of the matrix. How to implement it without ? (std::vector<std::vector<int>> m_matrix)
.resize()
Answer the question
In order to leave comments, you need to log in
#include<iostream>
#include<vector>
using namespace std;
template<typename T>
class Matrix
{
size_t cols;
size_t rows;
vector<vector<T>> m_matrix;
public:
Matrix(size_t c, size_t r) : cols{c}, rows{r}, m_matrix{}
{
m_matrix.reserve(cols);
for(auto i{0}; i < cols; ++i)
{
m_matrix.emplace_back(vector<T>(rows));
}
}
auto begin()
{
return m_matrix.begin();
}
auto end()
{
return m_matrix.end();
}
vector<T>& operator[](size_t i)
{
return m_matrix[i];
}
//...
};
int main()
{
Matrix<int> m(10,10);
m[5][5] = 5;
for(auto& c : m)
{
for(auto& e : c)
{
cout << e << ' ';
}
cout << endl;
}
return 0;
}
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 5 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question