We are given some int el_position
number which is a position of wanted by us element in flatened representation of our 2d vector (std::vector< std::vector<int> > matrix(5, std::vector<int>(4))
).
Meaning if we had such matrix
11 21 31 41 51
61 71 81 91 101
and we were given el_position
==
7
we would need to get second element of second row. Is it possible to do such thing withstd stl 2d vector? How to get value of element by given its position in flattened array?
Sure this is possible:
row = el_position % row_length;
col = el_position / row_length;
size_t size_y = matrix.front().size(); // to get your Y dimension
return matrix[el_position / size_y][el_position % size_y];
You just take one index of n/W
and the other - n%W
, where W
is the width (or row length, whatever). Note that in fact in the vector of vectors, you may have vectors of different length, so it's up to you to break things.
// Assuming fixed dimensions:
matrix[el_position/size][el_position%size];
/
is integer division, so computes the number of complete rows that we have to pass to find the row we're looking for and %
is the remainder from integer division, so finds how far we should offset into the row.
If one of your inner vectors isn't the same size this will fail. You can check this assumption with two asserts:
assert(matrix.size()); // needed for the front element to be valid
assert(std::count(matrix.begin(), matrix.end(), matrix.front().size())
== matrix.size()); // the count will be the number of elements
// if it's correct