Here - https://ru.stackoverflow.com/a/629964/228791 - the type of a three-dimensional matrix as vectors of vectors of vectors is used in the answer ...

using vector3d = vector<vector<vector<int>>>; 

In fact, it is more or less understandable, but the question is this - after all, each vector, for example, in a two-dimensional matrix, can be made its own size? If we declare an array

 double array[n][m]; 

then here at least in the cake hurt, but in each row will be the same number of columns. And with vectors, you can lengthen the vector, say ...

The question is - can you somehow make the means of the language itself so that the vector<vector<double>> matrix has fixed sizes? but at the same time its elements could be changed?

By fixed sizes, I mean that all the vectors inside always have the same size. Well, that is, I have such an NxM matrix, I could do, let's say, Nx2M , but so that I couldn’t even somehow change the size of 2M for some vectors, and 3 for others, so far I have only invented my own wrapper class write, but is it possible somehow without it?

  • Well, you need arrays) The vector is a vector and it can be changed. - vp_arth
  • @vp_arth Now, I will correct the question ... - Mikhailo

2 answers 2

Vectors are just dynamic arrays. Imagine that the way you are looking for exists and you used it.
How do you plan to add a layer to your matrix? You need to go through the cycle, and add something to each vector. In the middle of a cycle, your structure will be inconsistent.


Use std::array :

 array<array<array<int, l>, m>, n> 

Or, by analogy:

 template <class T, size_t n, size_t m, size_t l> using Matrix = array<array<array<int, l>, m>, n>; Matrix<float, 3, 4, 5> matrix; 

You can make a class of work with such matrices that return a new instance to any mutation.

  • Yes, but I incorrectly set the task, sorry. I meant that well, imagine that you can change these l, m, n in the course of work - and the matrix, and dynamic, and so that it is impossible to accidentally or specifically incorrectly change the lengths of individual rows or columns. - Mikhailo
  • @Mikhailo well, here you can’t do without writing your class with overriding operator[] - Flowneee
  • @Flowneee Yes, I wrote that I thought of writing my own class ... but I wondered if this could be achieved not by writing my own class, but using standard language tools ... - Mikhailo

If you need a multidimensional array with naturally unchanged sizes of subarrays, then you can implement it in the same way that embedded language arrays are implemented, i.e. through a one-dimensional array with recalculation of indices

 std::vector<double> v(n * m * l); 

with the subsequent access to the element [i][j][k] as

 v[i * m * l + j * l + k] // [(i * m + j) * l + k] 

I will not give you a ready-made class encapsulating such a recalculation of indices, but if you wish, you can implement it yourself.