How to simulate 2D int array in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

#define ROWS 3
#define COLS 4

class C2DArray {
	int rows, cols;
	int *p;
public:
	C2DArray(int i, int j);
	int &set(int i, int j);
	int get(int i, int j);
};

C2DArray::C2DArray(int i, int j)
{
	p = new int[i * j];
	if (!p) {
		cout << "Allocation Error" << endl;
		exit(1);
	}
	rows = i;
	cols = j;
}

int &C2DArray::set(int i, int j)
{
	if (i < 0 || i >= rows || j < 0 || j >= cols) {
		cout << "Out of Bounds" << endl;
		exit(1);
	}
	return p[i * cols + j];
}

int C2DArray::get(int i, int j)
{
	if (i < 0 || i >= rows || j < 0 || j >= cols) {
		cout << "Out of Bounds" << endl;
		exit(1);
	}
	return p[i * cols + j];
}

int main()
{
	C2DArray o(ROWS, COLS);

	for (int i = 0; i < ROWS; i++)
		for (int j = 0; j < COLS; j++)
			o.set(i, j) = i + j * 2;

	for (int i = 0; i < ROWS; i++)
	{
		for (int j = 0; j < COLS; j++)
			cout << o.get(i, j) << ' ';
		cout << endl;
	}

	return 0;
}


/*
run:

0 2 4 6
1 3 5 7
2 4 6 8

*/

 



answered Apr 12, 2018 by avibootz
edited Apr 12, 2018 by avibootz
...