简体   繁体   English

如何到达2d std :: vector(`std :: vector &lt;std :: vector的第N个元素 <T> &gt;`)?

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

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)) ). 我们给定了一个int el_position数字,这是我们元素在二维矢量的扁平化表示中所需的位置( 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. 然后给定el_position == 7我们将需要获取第二行的第二个元素。 Is it possible to do such thing withstd stl 2d vector? 可以用std 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). 您只需获取一个n/W索引,另一个n%W ,其中W是宽度(或行长,无论如何)。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM