Arrays

Hi can someone explain to me how the following can be done:

exampleArray[1] = 5

even though exampleArray is a 2d array? Ive come across this in some c++ source code ive been looking at and wasn't sure what it was doing. Is it that it is entering this '5' into the first position of the 2d array? The array was initially declared as:

std::vector<double> exampleArray(100*100);

any help or explanation is greatly appreciated
It's only conceptionally 2D.

When you think of 2D, you usually think it's organized like this (elements associated with an integer tuple):


0,0 0,1 0,2 0,3
1,0 1,1 1,2 1,3
2,0 2,1 2,2 2,3
3,0 3,1 3,2 3,3


But nothing stops you from organizing it like this (1D indices)


0+0 0+1 0+2 0+3
4+0 4+1 4+2 4+3
8+0 8+1 8+2 8+3
12+0 12+1 12+2 12+3
16+0 16+1 16+2 16+3


Where did you find two-dimensional array?!
There is declaration of a vector of doubles 10000 ( 100 * 100) elements of which are zero initialized. In fact it is a one-dimensional array which has 10000 elements that were initialized with zero.
thanks for that hanst99, in your example of organizing it like 1d indices, then how would you access the data at for example '8+3', would it be exampleArray[11]?
To access to any 2D matrix implemented as 1D you can do this:
 
myVector[i*COLS + j];
thanks aikon, so say i=1, j=3 and there are 10 columns. will this mean it points to the 13th position:

myVector[13] or alternatively:

myVector[10][3]
Given the following matrix:

1
2
3
4
(0,0)  (0,1) (0,2)
(1,0)  (1,1) (1,2)
(2,0)  (2,1) (2,2)
(3,0)  (3,1) (3,2)


(3,2)
i=3;
j=2;

If you have a 2D array, you may access to any posicion with myArray[ i ][ j ], beside, if you have a 1D array but you want the behave as a 2D you'd do myVector[i*COLS + j];


If you need a Matrix class in the future you can support it with this:
http://surprising-code.blogspot.com/p/matrix-templated.html
Last edited on
Topic archived. No new replies allowed.