It is frequently convenient to have dynamically allocated arrays whose size is computed at run time instead of being a constant. While GCC supports variable length arrays, they are not a part of the standard C language and are not allowed by most compilers. Therefore, the libgfx library provides some basic support for dynamically allocated array types. You can use this package by including the header file
#include <gfx/array.h>
There are three closely related templated array classes defined in this package:
template<class T> class array; template<class T> class array2; template<class T> class array3;The template type T determines the type of the elements stored in the array and the different classes support 1, 2, and 3 dimensional arrays. An array's dimensions must be declared when it is allocated, thus you can create instances of these arrays as in the following example:
array<int> u(L); array2<int> v(W, H); array3<int> w(W, H, D);Note that unlike C arrays (e.g., int u[L]) dimensions can be specified by any arbitrary expression, such as a function call.
Arrays can always be implicitly converted to pointer types. In other words, an object of type array<int> can be used anywhere a variable of type int* can be used. Elements of the array can be accessed using the standard [] bracket notation. For the 2 and 3 dimensional arrays, elements are accessed in the following manner
array2<int> v(3, 3); v(0, 0) = 24; array3<int> v(3, 3, 3); v(0, 0, 0) = 24;And the number of elements of an array can always be determined by calling the length() method. For dimensions higher than 1, the width(), height(), and depth() methods are provided.
In addition to the basic dynamically allocated array, this package also provides support for variably sized arrays. These arrays provide the additional feature that they automatically expand to accommodate new elements as they are added to the array. Thus, it is in some ways a light-weight relative of the std::vector class provided in the C++ Standard Template Library.
template<class T> class varray : public array<T>;The size of the array is determined by two related methods: length() returns the number of elements in the array and total_space() returns the number of elements currently allocated, which will always be larger than length().
New elements can be added to the array using the following methods:
void add(const T& value); // Adds new element and copies x into it. T& add(); // Add new element and return it.The array will automatically grow itself if no space is available for the new element. Note that you can force the array to increase in size to n elements by invoking the methods room_for(n).
void reset(); // Remove all elements T& drop(); // Remove the last element void drop(int d); // Remove the last d elements void remove(int i); // Remove element i (may reorder array) void remove_inorder(int i); // Remove element i and do not reorder arrayNote that the array will never shrink in response to element removals.