Skip to content

Instantly share code, notes, and snippets.

@mgarg1
Created October 8, 2014 04:53
Show Gist options
  • Save mgarg1/fbcfcecfdcf693662188 to your computer and use it in GitHub Desktop.
Save mgarg1/fbcfcecfdcf693662188 to your computer and use it in GitHub Desktop.
Overloading subscript operator [ ] for 2-d arrays
#include <iostream>
#include <cstddef>
using namespace std;
template <typename T>
class Array2D {
public:
Array2D(size_t nr, size_t nc) : n_rows(nr), n_cols(nc), data(new T[n_rows*n_cols]) {}
~Array2D() { delete [] data; }
private:
class Helper {
friend class Array2D;
private:
Helper(Array2D *array, size_t i_) : the_array(array), i(i_) {}
public:
T &operator[](size_t j) {
if (j >= the_array->n_cols) { cout << "OOR2" << endl; }
return *(the_array->data + i*the_array->n_cols + j);
}
private:
Array2D *the_array;
const size_t i;
};
// friend class Helper;
public:
Helper operator[](size_t i) {
if (i >= n_rows) { cout << "OOR1" << endl; }
return Helper(this, i);
}
private:
const size_t n_rows, n_cols;
T *data;
};
int
main() {
Array2D<int> a(3, 4);
a[1][2] = 1234;
cout << a[1][2] << endl;
a[5][0] = 1;
a[0][5] = 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment