How to get to the Nth element of a 2d std::vector

2019-07-22 09:17发布

问题:

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?

回答1:

Sure this is possible:

 row = el_position % row_length;
 col = el_position / row_length;


回答2:

size_t size_y = matrix.front().size(); // to get your Y dimension
return matrix[el_position / size_y][el_position % size_y];


回答3:

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.



回答4:

// 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