I'm creating a class called "matrix" that has a class member of std::vector<std::vector<T>>
, what is the best optimized way to set its size in the class constructor? I'm using matrix_.resize(m)
in the constructor for m
rows and then using a for loop to set its row values(matrix m x n
). The question I have is:
Is it a good approach to use .resize()? I heard it is not efficient but I can't think of anything else
When I use
std::vector<std::vector<T>> = matrix_;
, for example and I usematrix_.resize(m)
, thematrix_
now will have "m" spaces for "m"std::vector<T>
objects, but howmatrix_
will manage the memory if it doesn't know the size of its objects(std::vector<T>
)? What if each objects are size(1000) or larger?
#include <iostream>
#include <vector>
// Matrix of shape m x n, 'm' lines and 'n' columns
template <typename T>
class matrix {
private:
typedef T value_type;
typedef std::vector<value_type> row;
std::vector<row> matrix_;
public:
// Default constructor, initializes a matrix of size 1x1, with element 0.
matrix() {
matrix_.resize(1);
row temp = {0};
matrix_[0] = temp;
};
matrix(size_t m, size_t n) {
matrix_.resize(m);
// Appends 'm' rows to the matrix_
for (size_t i = 0; i < m; i++) {
row temp(n); // Creates a row of 'n' columns
matrix_[i] = temp;
}
}
value_type& at (size_t m, size_t n) {
return matrix_[m][n];
}
};
int main() {
matrix<double> first(2, 2);
first.at(0, 0) = 3.3;
first.at(0, 1) = 5.2;
first.at(1, 0) = 8.9;
first.at(1, 1) = 1.4;
return 0;
}