Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ multidimensional array operator

Tags:

c++

it is possible to overload somehow operator for multidimensional array?

Something like:

class A {
  ...
  int& operator[][] (const int x, const int y);
  ...
}
like image 969
graywolf Avatar asked Oct 18 '12 15:10

graywolf


People also ask

Does C allow multidimensional arrays?

In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];

What is 2dimensional array in C?

A two-dimensional array in C can be thought of as a matrix with rows and columns. The general syntax used to declare a two-dimensional array is: A two-dimensional array is an array of several one-dimensional arrays. Following is an array with five rows, each row has three columns: int my_array[5][3];

What is multi-dimensional array in C explain with example?

A multi-dimensional array is an array with more than one level or dimension. For example, a 2D array, or two-dimensional array, is an array of arrays, meaning it is a matrix of rows and columns (think of a table). A 3D array adds another dimension, turning it into an array of arrays of arrays.


1 Answers

Nope, that is not possible. There are two alternatives, though:

You can have operator[] return an array of a smaller dimension (For a 3D array, it will return a 2D array, for a 2D array it will return a 1D array, and for a 1D array, it will return a single element). Then you can "string them together" with the syntax you want. (arr[x][y][z])

Alternatively, you can overload operator(), because that can take multiple arguments.

Then you can use it like this, to index into a 3D array for example: arr(x,y,z)

But you can't overload [][] or [][][] as a single operator.

like image 126
jalf Avatar answered Sep 20 '22 19:09

jalf