L
L
Leevz2018-09-19 18:46:32
C++ / C#
Leevz, 2018-09-19 18:46:32

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

1 answer(s)
R
Roman, 2018-09-19
@Leevz

matrix
#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;
}

OUT:
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

just why? If present (at least):
std::valarray
AND
std::slice
boost::numeric::ublas

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question