Greetings!
I have some data included in array with 100 rows and 100 columns.
i need to roll through all of rows and columns, but i dont know actual columns quantity
How can i get quantity of columns,as i get quantity of rows by size()
#include<iostream>
using namespace std;
int main()
{
// an array with 3 rows and 2 columns.
int x[100][100] = {{0,1}, {2,3}, {4,5}};
}
In C/C++, in a 2D array, each "row" has the exactly same number of "columns".
You can get the total size of array, in bytes, with the sizeof() operator. To get the number of elements, in each dimension, some calculations are needed. This is best done with a helper macro. See here, for an example: https://stackoverflow.com/a/34135270
No, you don't! At least if the array was defined as in your example code ;-)
In C/C++, a "2D" array is defined as int array[N][M], and in this array each of the N "rows" has exactlyM "columns". It's as simple as that. It is not possible to have different number of "columns" in a "row".
If you really want a different number of columns for each row, then instead of using a "2D" array, you have to use an array of pointers and allocate a separate buffer, e.g. via new operator, for each row:
1 2 3 4 5 6
int *array[N];
for (size_t i = 0; i < N; ++i)
{
size_t m = get_number_of_columns_for_row(i);
array[i] = newint[m];
}
Don't forget to delete[] the buffers, or you will get a memory leak!
You could just have a regular 2D array with a maximal number of available columns and only use as many columns as necessary.
Keeping track of the number of columns used per row can be done any number of ways: a sentinal value to terminate the row, using the first elemnt of the row for the count, using yet another array for number of rows, using a large struct with size+array for each row, etc.
The vector of vector is your nicest option in C++, though...