Finding the amount of rows and columns for a 2-D array in C++
Asked Answered
S

2

9

I know in C++ you can get a arrays amount of rows and columns with:

 int rows = sizeof array / sizeof array[0];
 int cols = sizeof array[0] / sizeof array[0][0];

However is there any better way to do this?

Selenaselenate answered 10/2, 2013 at 8:3 Comment(1)
Yes. Since this is C++ use vector.Mendel
S
6

In C++11 you can do this using template argument deduction. It seems that the extent type_trait already exists for this purpose:

#include <type_traits>
// ...
int rows = std::extent<decltype(array), 0>::value;
int cols = std::extent<decltype(array), 1>::value;
Spradling answered 10/2, 2013 at 8:15 Comment(0)
L
0

Also you can use sizeof() function;

int rows =  sizeof (animals) / sizeof (animals[0]);
int cols = sizeof (animals[0]) / sizeof (string);

Example:

#include <iostream>

using namespace std;

void sizeof_multidim_arrays(){
    string animals[][3] = {
        {"fox", "dog", "cat"},
        {"mouse", "squirrel", "parrot"}
    };
    int rows =  sizeof (animals) / sizeof (animals[0]);
    int cols = sizeof (animals[0]) / sizeof (string);
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            cout << animals[i][j] << " " << flush;
        }
        cout << endl;    
    }
}

Output:

fox dog cat 
mouse squirrel parrot
Linesman answered 2/11, 2019 at 22:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.