Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Container of vectors with fixed, but runtime-determined length in C++

Tags:

c++

stl

Is there a way to construct a container that contains vectors of the same length, but with this length determined at runtime (i.e. container construction time)?

This question has already been asked as C++: Vector of fixed but runtime defined length arrays with the motivation of saving memory. My motivation is different, I would like to avoid potential bugs without having each function that uses the container first having to verify that all elements are of the same length.

(In my specific case, I am using an std::unordered_map, but I assume that the answer is independent of the container type. I'm also happy to use a custom class instead of unordered_map if that helps).

like image 439
Nikratio Avatar asked Jan 01 '26 03:01

Nikratio


1 Answers

Yes, of course you can. As usual, the best solution is to create a new type that maintains the invariants you need through its interface.

The easiest would be to simply create a new type for the subcontainers which ensures that the length of your vector is never modified (i.e. does not provide any functions that allow to add or remove elements). Then you can use that type in your container of containers, whichever that is.

like image 155
Acorn Avatar answered Jan 03 '26 16:01

Acorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!