Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Oct 26, 2001

Two Dimensional Array Simulation Using One Vector Object


To simulate a Matrix class with M*N elements, initialize a vector with M*N elements and overload the () operator such that Foo(i,j) returns Foo[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 and
Index(M[0],M[1],M[2],..) = M[0]*M[1]*M[2]-1
John Alexiou
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date