  Advertiser Disclosure
 TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow    Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Oct 26, 2001

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

# 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, Foo(2,1) to Foo, 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*(j-1+M*(k-1+...)) such that Index(1,1,1..) = 0 and
Index(M,M,M,..) = M*M*M-1
``````
John Alexiou Submit a Tip Browse "C++" Tips Browse All Tips   Comment and Contribute

(Maximum characters: 1200). You have 1200 characters left.    Thanks for your registration, follow us on our social networks to keep up-to-date