devxlogo

Two Dimensional Array Simulation Using One Vector Object

Two Dimensional Array Simulation Using One Vector Object

To simulate a Matrix class with M*N elements, initialize a vector withM*N elements and overload the () operator such that Foo(i,j) returnsFoo[i-1+M*(j-1)]. This way Foo(1,1) is equivalent to Foo[0], Foo(2,1) to Foo[1], Foo(M,1) to Foo[M-1], Foo(1,2) to Foo[M] and finaly Foo(M,N) to Foo[M*N-1].

The standard matrix notation of {Aij} will be coded in C++ as A(i,j) instead of A[i-1][j-1]. This uses only 1 vector class and not a vector of vectors.

This idea can be extended into multidimensional arrays easily. Given that there are N dimensions, and each contains M[i] elements (i=0,1..N-1) then an z=Index(i,j,k,..) member function can be defined such that Foo(i,j,k,..) returns Foo[Index(i,j,k,..)]. The index multiplexing function Index(i,j,k,..) has to use the va_arg macro to access any number of dimension indexes. It would return a sum like this:

 i-1+M[0]*(j-1+M[1]*(k-1+...)) such that Index(1,1,1..) = 0 andIndex(M[0],M[1],M[2],..) = M[0]*M[1]*M[2]-1
See also  Is Machine Learning Automating Creativity in Graphic Design?
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist