When should dynamic two-dimensional data use nested vectors, flat contiguous storage, or a non-owning multidimensional view?
Show answer and explanation
A vector<vector> owns each row separately, naturally supports jagged row lengths, and makes row-level mutation easy, but it usually performs multiple allocations and does not provide one contiguous matrix. A flat vector owns rows times columns elements in one allocation, improving transfer, serialization, and many cache-sensitive traversals; it needs checked dimension multiplication plus explicit index and stride rules. A non-owning view separates indexing from ownership and can represent contiguous, strided, or submatrix layouts, but the underlying storage must outlive the view. C++23 std::mdspan is such a multidimensional view; C++20 code can provide a small checked view or span-based row access. Choose from shape mutability, interoperability, locality, allocation, bounds, and lifetime requirements rather than syntax alone.
A vector<vector> owns each row separately, naturally supports jagged row lengths, and makes row-level mutation easy, but it usually performs multiple allocations and does not provide one contiguous matrix. A flat vector owns rows times columns elements in one allocation, improving transfer, serialization, and many cache-sensitive traversals; it needs checked dimension multiplication plus explicit index and stride rules. A non-owning view separates indexing from ownership and can represent contiguous, strided, or submatrix layouts, but the underlying storage must outlive the view. C++23 std::mdspan is such a multidimensional view; C++20 code can provide a small checked view or span-based row access. Choose from shape mutability, interoperability, locality, allocation, bounds, and lifetime requirements rather than syntax alone.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.