I'd like to use std::array
from C++11 as a field of my own class. It takes two template parameters (first defines type of data, second defines size of an array).
But I know the second parameter only in constructor. I'm not familiar with C++11 standard, but I suppose that it's impossible to set a template parameter during execution.
Are there any alternatives for std::array
? std::vector
is probably a little too much, cause I will never change the size of it.
std::array is a container that encapsulates fixed size arrays. This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member. Unlike a C-style array, it doesn't decay to T* automatically.
std::array provides many benefits over built-in arrays, such as preventing automatic decay into a pointer, maintaining the array size, providing bounds checking, and allowing the use of C++ container operations.
The general syntax of declaring an array container is: array<object_type, size> array_name; The above declaration creates an array container 'array_name' with size 'size' and with objects of type 'object_type'.
std::array contains a built-in array, which can be initialized via an initializer list, which is what the inner set is. The outer set is for aggregate initialization.
std::vector
is the simplest thing to use; although as you say, it does waste a few bytes if you'll never need to resize it.
std::unique_ptr<T[]>
, initialised using the result of new T[size]
, would be the most efficient thing; it should be the same size as a pointer, and will delete the allocated memory for you when it's destroyed. It's not copyable, though; you'll need to provide a copy constructor for your class if you want it to be copyable. It's also less convenient than std::array
and std::vector
, since it doesn't have the interface of a standard container. You could perhaps write a STL-style wrapper for it if you need that; but I'd just use std::vector
in that case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With