How to get to the Nth element of a 2d std::vector (`std::vector< std::vector<T> >`)?

≡放荡痞女 提交于 2019-12-11 07:13:59

问题


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


来源:https://stackoverflow.com/questions/8094467/how-to-get-to-the-nth-element-of-a-2d-stdvector-stdvector-stdvectort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!