![]() | |
![]() ![]() |
![]() | Imperfect C++ Practical Solutions for Real-Life Programming By Matthew Wilson |
Table of Contents | |
Part Six. Extending C++ |
Chapter 33. Multidimensional ArraysAs we saw in section 14.7, C and C++ do not support multidimensional arrays of dynamic size, except where all but the most significant dimension is of constant size. In other words, you can do the following: void f(int x) { new byte_t[x]; } but not:
void f(int x, int y, int z)
{
new byte_t[x][y][z]; // Error
}
Creating a multidimensional array can only be in this form:
const size_t Y = 10;
const size_t Z = Y * 2;
void f(int x)
{
new byte_t[x][Y][Z];
}
This can be quite a restriction. For example, a couple of years ago I was working on a multimedia product user interface where the layout of the interface was dynamically retrieved from a central server over the Internet. The layout could be any possible combination of video, text, dialog, image, and other visual controls within rectangles within rectangles to arbitrary depth sufficient to emulate an unstructured layout. All these levels of rectangles cried out "rectangular array," but because neither dimension was fixed or anticipatable, the built-in array support was not up to the job.
You may not regard this as an imperfection, since one of the principles of C++ is to favor the provision of functionality by the addition of libraries rather than library features, and there exist such libraries, as we'll see later in this chapter. However, as I will demonstrate, it is not possible to fully emulate the syntax of the built-in arrays, although we can come pretty close. Clearly the answer to this problem lies in custom containers. As we learned in section 14.7, the language supports the taking of slices, so this is eminently feasible. We'll look at several mechanisms for providing N-dimensional arrays in this chapter.[1]
|
![]() | |
![]() ![]() |