Is there a C++ type that acts like a "dynamically sized non resizable array"? This kind of type can be thought of as one of two things:
vector<T>
but without resize
, push_back
, etc. array<T,N>
but where N
is dynamic and not static.I do not want a solution that only works if the type of the elements within the array is a non-copyable type. I want a generic solution.
A dynamic array is an array with a big improvement: automatic resizing. One limitation of arrays is that they're fixed size, meaning you need to specify the number of elements your array will hold ahead of time. A dynamic array expands as you add more elements. So you don't need to determine the size ahead of time.
Dynamic arrays in C++ are declared using the new keyword. We use square brackets to specify the number of items to be stored in the dynamic array. Once done with the array, we can free up the memory using the delete operator. Use the delete operator with [] to free the memory of all array elements.
A dynamic array is a random access, variable-size list data structure that allows elements to be added or removed. It is supplied with standard libraries in many modern programming languages. Dynamic arrays overcome a limit of static arrays, which have a fixed capacity that needs to be specified at allocation.
Yes, there (pretty much) is. std::unique_ptr<T[]>
. The primary template has a partial specialisation for this case, which provides the appropriate interface (operator []
, no operator *
etc.)
Alternatively, you can wrap std::vector
in your own class and restrict its interface. You could even do that by deriving a class from std::vector
using non-public inheritance and publishing only the relevant parts of its interface:
template <class T, class A = std::allocator<T>>
struct FixedVector : private std::vector<T, A>
{
using FixedVector::vector::vector;
using FixedVector::vector::operator=;
using FixedVector::vector::get_allocator;
using FixedVector::vector::at;
using FixedVector::vector::front;
using FixedVector::vector::back;
using FixedVector::vector::data;
using FixedVector::vector::begin;
using FixedVector::vector::cbegin;
using FixedVector::vector::end;
using FixedVector::vector::cend;
using FixedVector::vector::empty;
using FixedVector::vector::size;
using FixedVector::vector::operator[];
};
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