How best to store a dynamic matrix: std::vector<std::vector<T>> , std::vector<std::vector<T>*> or std::vector<std::unique_ptr<std::vector<T>>> , where T - a) trivial type; b) non-trivial type T - a) trivial type; b) non-trivial type ?

  • 1 - To store the values ​​of objects, as a rule, easier than pointers to them. 2 - store non-trivial types in any case according to the pointer. 3 - storing smart pointers ( std::unique_ptr ) is usually simpler than regular pointers. - yrHeTaTeJlb
  • Well, this is for the "spherical matrix in vacuum" :) In practice, there are always any "but" - yrHeTaTeJlb
  • @yrHeTaTeJlb just use the first option everywhere, where it looked; but even the vector of vectors of trivial types is expensive to store? - qwerty
  • he himself personally did not notice the difference between pointers and vector <vector <map >> and others when working with the internal vector <T> - J. Doe
  • @qwerty Not so expensive. For example, in VC ++, the overhead of vector memory is about 12 bytes — regardless of the number of elements. If you work with pointers - what will change? For an extra pointer for each vector in the second dimension + extra indirectness when handling. - Harry

2 answers 2

Actually, as they say, depends on ... Personally, I would prefer the first of the above options - because of the simplicity of the work, the natural reference to the elements through two indexing operations, the absence of overhead costs for indirect calls.

But, quite possibly, I would use some other (perhaps my own) option - if there was any information about the matrix - what operations are planned, dense / sparse, how important is efficiency at work, how often will (and whether) change the size of the matrix ...

    How best to store a dynamic matrix

    The matrix of any dimension is well displayed in a one-dimensional vector. Your task will be reduced to just playing with indexes.