Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically sized non resizable array [duplicate]

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.

like image 976
tohava Avatar asked Mar 05 '15 12:03

tohava


People also ask

What is dynamic sized array?

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.

How do you declare an array dynamically?

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.

What is dynamic array in Oop?

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.


Video Answer


1 Answers

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[];
};
like image 136
Angew is no longer proud of SO Avatar answered Oct 20 '22 00:10

Angew is no longer proud of SO