Michael Taufen
Michael Taufen

Reputation: 1704

C++ Iteration on nonuniform multidimensional arrays

Consider the following C++ code example:

int array_1[] = {5,6,7};
int array_2[] = {6,7,8,9};
int array_3[] = {2,3};

int* meta_array[] = {array_1, array_2, array3};

Now I want to iterate over all of the elements in the sub arrays of meta_array without causing a seg fault.

The problem, of course, is that I have no way to get the size of the arrays to avoid overstepping their bounds.

I can do sizeof array_1 / sizeof array_1[0] to get the size of a common 1-dimensional array pretty quickly, but once I'm in the meta_array, every element has been converted to a pointer, and so sizeof will return the byte size of the pointer instead of the entire array. Thus, sizeof meta_array[0] / sizeof meta_array[0][0] doesn't really do much to help my cause.

Is there a standard solution to iterating over nonuniform multidimensional arrays out there already, or should I just go ahead and use std::vector?

Upvotes: 0

Views: 628

Answers (3)

Steven Martin
Steven Martin

Reputation: 3

If you're deadset against using vector, you could also maintain the lengths in an array:

#include <iostream>
#define ARRSIZE(X) sizeof(X) / sizeof(X[0])

int main() {
    int array_1[] = { 5,6,7 };
    int array_2[] = { 6,7,8,9 };
    int array_3[] = { 2,3 };

    int* meta_array[] = { array_1, array_2, array_3 };
    int meta_array_lengths[] = { ARRSIZE(array_1), ARRSIZE(array_2), ARRSIZE(array_3) };

    for (int outer = 0; outer < ARRSIZE(meta_array); outer++) {
        for (int inner = 0; inner < meta_array_lengths[outer]; inner++) {
            std::cout << meta_array[outer][inner] << " ";
        }
        std::cout << '\n';
    }

    return 0;
}

Output:

5 6 7
6 7 8 9 
2 3 

Upvotes: 0

nerozehl
nerozehl

Reputation: 473

You would find extreme benefit from Boost.MultiArray

Upvotes: 0

vulkanino
vulkanino

Reputation: 9124

use std::vector.

or, use a "closing" number but you must be sure there will be no elements with that value, ever.

int array_1[] = {5,6,7,-1};
int array_2[] = {6,7,8,9,-1};
int array_3[] = {2,3,-1};

int*  meta_array[] = 
{
  array_1, 
  array_2, 
  array_3,
  NULL
};

for(int i=0; meta_array[i] != NULL; ++i)
{
   for(int j=0; meta_array[i][j] != -1; ++j)
       printf("%d",  meta_array[i][j]);
   printf("\n");
}

Upvotes: 2

Related Questions