Does someone know the way to define constant-sized vector?
For example, instead of defining
std::vector<int>
it will be
std::vector<10, int>
It should be completely cross-platformed. Maybe an open source class?
Does someone know the way to define constant-sized vector?
For example, instead of defining
std::vector<int>
it will be
std::vector<10, int>
It should be completely cross-platformed. Maybe an open source class?
The std::vector can always grow dynamically, but there are two ways you can allocate an initial size:
This allocates initial size and fills the elements with zeroes:
This allocates an initial size but does not populate the array with zeroes:
This ---->
std::vector<10, int>
is invalid and causes error. But the new C++ standard has introduced a new class; the std::array. You can declare an array like this:The
std::array
has constant size and supportsiterator/const_iterator/reverse_iterator/const_reverse_iterator
. You can find more about this class at http://cplusplus.com/reference/stl/array/.A
std::vector
is a dynamic container, there is no mechanism to restrict its growth. To allocate an initial size:C++11 has a
std::array
that would be more appropriate:If your compiler does not support C++11 consider using
boost::array
:There is no way to define a constant size vector. If you know the size at compile time, you could use C++11's std::array aggregate.
If you don't have the relevant C++11 support, you could use the TR1 version:
or boost::array, as has been suggested in other answers.
This is an old question but if someone just needs constant-size indexed container with size defined at runtime, I like to use unique_ptr:
P.s. This is C++14.
Use std::array c++11
For better readability you can make typedef: