c++ how to count arrays within an array

263 Views Asked by At

suppose I have this code :

int arr[] = {{1, 4}, {2}, {3, 2, 6}};

how do I count the number of arrays within an array, which in this case would be 3. if the code dosen't work is there a way to get the answer with other methods?

i've searched on google and read articles

2

There are 2 best solutions below

0
On

Your code can't work. You're declaring singe-dimensional array of type int and try to initialize each int element with a nested brace-enclosed initializer list. More of, an array may contain elements ONLY of same type. Arrays of different size are different type, so what you tried to imply is outright impossible.

You can use one of dynamic containers in nested way, e.g. std::vector<std::vector<int>>. But for sake of knowledge or absolute, inescapable need to have a statically-sized array:

 int arr[][3] = {{1, 4}, {2}, {3, 2, 6}};

Note, that in this case all elements are arrays of size 3. Rest of elements are initialized to 0. For any array following is true:

count_of_subarrays = sizeof(arr)/sizeof(arr[0]);

As long as arr name here is actually an array and not a pointer, it would work. You divide total size of array by size of its first element. Since C++17 there is a helper which does that:

count_of_subarrays = std::size(arr);

Ragged, but statically-sized arrays may be implemented by creating a more complex structure, eg. actually storing sizes of elements in your structure. I.e. you would have an array of element values, an array of sizes\indices and re-defined operator[]

8
On

A one-dimsional array can not contain other arrays as its elements.

You could use for example std::initializer_list<int> as the element type instead of the type int.

Here is a demonstration program.

#include <iostream>
#include <initializer_list>
#include <iterator>

int main()
{
    std::initializer_list<int> arr[] = { {1, 4}, {2}, {3, 2, 6} };

    std::cout << "The array contains " << std::size(arr) << " lists\n";

    for (const auto &list : arr)
    {
        std::cout << '\t' << std::size(list) << ": ";
        for (const auto &item : list)
        {
            std::cout << item << ' ';
        }

        std::cout << '\n';
    }
}

The program output is

The array contains 3 lists
        2: 1 4
        1: 2
        3: 3 2 6

Otherwise you could declare a two-dimensional array like for example

int arr[][3] = {{1, 4}, {2}, {3, 2, 6}};

In this case each element of the array has the type int[3].

Again you can use the standard C++ function std::size declared in the header <iterator> to get the number of elements in the array. Or you could simply write

const size_t N = sizeof( arr ) / sizeof( *arr );

N will be equal to 3.

Another approach is to use standard container std::vector.

For example

std::vector<std::vector<int>> arr = { {1, 4}, {2}, {3, 2, 6} };

You may use the same standard function std::size( arr ) or member function size like arr.size().