You can use std::vector<std::vector>>
as suggested and take their .size()
methods, however that is not the most memory friendly.
I'd suggest wrapping your array of arrays, aka pointer of pointers in a small, dedicated class which internally keeps track of the sizes, allows you to access the raw data and also has a getWidth
and getHeight
function. You can also easily give it convenient functions like .setAll(T value)
and use templates to support any data type.
// Example program
#include <iostream>
#include <string>
template<class T>
class RawGrid
{
private:
int width, height;
public:
RawGrid(int width, int height) : width(width), height(height)
{
data = new T*[width];
for(int i = 0; i < width; i++)
data[i] = new T[height];
}
~RawGrid()
{
if (data)
{
for(int i = 0; i < width; i++)
delete[] data[i];
delete[] data;
}
}
int getWidth() {
return(width);
}
int getHeight() {
return(height);
}
T** data = nullptr;
};
int main()
{
RawGrid<int> grid(100, 50);
grid.data[10][25] = 20;
std::cout << "Data value: " << grid.data[10][25] << "!\n";
std::cout << "Width: " << grid.getWidth() << "!\n";
std::cout << "Height " << grid.getHeight() << "!\n";
}