Is there a way to implement an operator like [][]
for a 1D array?
I want to change the implementation of a 2D vector to a 1D vector in my code (cause this increases the execution speed by about %50 in my program). 2D vector supports [y][x]
. How can I have such functionality for a 1D vector?
I can do it like this:
const size_t Y_Axis { 20 };
const size_t X_Axis { 30 };
std::vector<char> vec( Y_Axis * X_Axis );
size_t row { 5 };
size_t col { 28 };
vec[ row * X_Axis + col ] = 't'; // assign a value to a specific row-column
However, typing this formula multiple times throughout a source file seems like violating DRY (don't repeat yourself). How can I do this in an efficient and idiomatic way? I want to hide the complexity and make things a bit abstracted just like operator[][]
of 2D vector does.