View Single Post
Old 03-23-2005, 11:35 PM   #8 (permalink)
Rangsk
Crazy
 
Location: San Diego, CA
Quote:
Originally Posted by skaven
kel's idea is pretty good if you're forced to use C-style arrays. Simply use something other than a for-loop to iterate over the array:

Code:
int x = 0;
while(your_array[x] != NULL) {
    // do something with your_array[x]
    x++;
}
Of course this requires that you be unusually vigilant about ensuring that the NULL is always present at the end of the array. If you accidentally write a value to the last value of the array, the code will work fine until it hits one of these while loops, at which point you'll exit the bounds of the array (and probably segfault).
This doesn't work if 0 is an allowed value in the array. It's really only valid for strings.

Generally when working with arrays, you have to pass the size of the array.

As for 2d arrays, to create one of dynamic size you have to do this:

Code:
int ** my2darray = new (int*)[x_size];
for (int c = 0; c < y_size; c++)
{
  my2darray[c] = new int[y_size];
}
And so to delete it:
Code:
for (int c = 0; c < y_size; c++)
{
  delete my2darray[c];
}
delete my2darray;
As for vectors, I highly recommend looking a few things:
push_back()
iterators

Let's say T is a type and I have:
vector<T> myVector;

At the start, myVector.size() is 0 since it has no values.
I can add values of type T to end of the vector with:
myVector.push_back(value);

Now let's say I want to loop through all the elements in the vector. The most efficient way is to use iterators:
Code:
for (vector<T>::iterator i = myVector.begin(); i != myVector.end(); i++)
{
  // (*i) contains the current value.  You can basically treat i as a pointer
}
You can also make a reverse_iterator:
Code:
for (vector<T>::reverse_iterator i = myVector.rbegin(); i != myVector.rend(); i++)
{
  // This loops through the vector backwards
}
Have fun
__________________
"Don't believe everything you read on the internet. Except this. Well, including this, I suppose." -- Douglas Adams
Rangsk is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62