Wednesday, March 18, 2009

Lesson 5: Arrays

In programming, you are most likely to need a collection of variables. Let’s say I want to store a register of the different people in class:

Register[0] = “John”
Register[1] = “Mary”
Register[2] = “Ah Seng”
Register[3] = “Ah Beng”

Register[n-1] = “Ben”

Well you get the picture. This is where arrays come in.

In C++, there are 2 ways to declare an array: A Vector (Under STL) and an Array (inbuilt). I will teach you Vector since it is more widely used and is dynamic (i.e., easier to understand) than Arrays.

To declare a vector:

vector<[type]> [name];

or

vector<[type]> [name]([size], [fill]);

where size is size of the array (i.e. the n), and the fill is the constant you want to fill those empty “slots”.

To set a value manually after constructing the array, you just do this:

[name][n] = “hi”;

//eg
vector basket(3);
basket[0] = “apples”;
basket[2] = “grapes”;

(Note that arrays are always zero-based, so the max reference is 2, and the starting is 0.)

To iterate (loop) through an array, we use loops:

vector bla(5,20);

for (int i = 0; i < bla.size(); i++) {
cout << bla[i] << endl;
}


This is good particularly if you want to search for something in the array or do processing (for e.g. image convolution).

What if your array is 2D, i.e. a picture’s pixel values? Then you use multiarrays, or rather, a vector that contains another vector to form a 2D image, or a single extremely long vector. Multiarrays are referenced as such:


[name] [x + y * w];
//x = current x pos
//y = current y pos
//w = width of multiarray

To give you an example of how to use them:


//This prints out a 50 X 20 multiarray of 20s
int w = 20, h = 50;
vector bla(w + h * w,20);

for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
cout << bla[x + y * w] << " ";
}
cout << endl;
}


So that’s arrays (rather, vectors) in a nutshell. Ciao!

No comments:

Post a Comment