I made a class to convert the index between 2D and 1D arrays. For example, between
{1,3,5,7,9,11} and {{1,3},{5,7},{9,11}}
- When
i
is 0,xy
should be (0,0) - When
i
is 1,xy
should be (0,1) - When
i
is 2,xy
should be (1,0)
And so on...
I would be able to convert between the i
-index and the xy
-index to find get the equivalent location. I feel like this piece of code may be too long for its purpose.
class IndexConv {
public:
IndexConv(int rows, int cols);
bool check_i(int i) const;
bool check_xy(int x, int y) const;
pair<int, int> to_xy(int i) const;
int to_i(int x, int y) const;
private:
const int rows_;
const int cols_;
};
IndexConv::IndexConv(int rows, int cols)
:rows_(rows), cols_(cols) {}
bool IndexConv::check_i(int i) const
{
return i>=0 || i<rows_*cols_;
}
bool IndexConv::check_xy(int x, int y) const
{
return x>=0 && y>=0 && x<rows_ && y<cols_;
}
pair<int, int> IndexConv::to_xy(int i) const
{
if(!check_i(i)) throw out_of_range("IndexConv: i out of bounds.");
int x = i/cols_;
int y = i-x*cols_;
return make_pair(x,y);
}
int IndexConv::to_i(int x, int y) const
{
if(!check_xy(x,y)) throw out_of_range("IndexConv: xy out of bounds.");
int i = x*cols_+ y;
return i;
}