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