Finding the length of a row of a non-uniform 2D array

Hi forum,

I have a non-uniform two dimensional array and I want to find the number of elements in a certain row.

Let's say that my array is the one below, and I want to find the length of the third row(so the number of columns).

1
2
3
4
5
int array[3][4] = {
        {"1", "2", "3"},
        {"4", "5", "6", "7"},
        {"8"},
    };


Any help is really appreciated
I'm not actually sure you can do this. Your array declaration allows for 4 columns, irrespective of whether you set them or not.

Are you sure that you couldn't use a 1-d array of vectors? - then you can just use the size() member function to find the number of elements in each vector (i.e. the number of "columns").
OK so the full context:

I am making a small role-playing game. All the name of the monsters are saved in a 2D array. Each row contains the monsters for each level, since he can't 'fight' the same monsters at level 1 and 100. The monster that he is going to fight is a random element of the row of his level. So if the character is level 4, he will fight a random monster from the fourth row. I wanted to know the length of the row to limit the range of the random number.

Are you sure that you couldn't use a 1-d array of vectors?

Maybe if I store all the elements in a 1D array I can randomly pick one and then if it doesn't meet some requirements(character level is smaller than monster level), another random number is chosen.

Thanks for your help.
If you prefer to keep the multi-dimensional array you could also "mark" the effective end of a row with a number that has no other use (-1 perhaps). This is a bit like the null-terminator used to signify the end of Cstrings.
Last edited on
Note, the element-type of your example array is int, but you (attempt to) initialize them with string literals.

lastchance did mean this kind of "1D array of vectors":
1
2
3
4
5
6
7
8
std::vector<int> array[] = {
        {1, 2, 3},
        {4, 5, 6, 7},
        {8}
    };

int level = 2;
std::cout << "Level " << level+1 << " has " << array[level].size() << " monsters\n"; 



Topic archived. No new replies allowed.