交换内部和外部向量
我定义了 myObjects 向量的向量,本质上创建了一个二维数组。我想转置这个数组,使行变成列,列变成行。显然我可以在双 for 循环中做到这一点,但这看起来非常不优雅并且会非常慢。我想知道 C++ 或 STL 中是否有一些聪明的东西可以让我快速有效地交换内部和外部向量,而不是编写......
for (int iRow = 0; iRow < nRows; ++iRow)
{
for (int iCol = 0; iCol < nCols; ++iCol)
{
myNew2DArray[iCol][iRow] = myOriginal2DArray[iRow][iCol];
}
}
I have a vector of vector of myObjects defined, creating essentially a 2D array. I would like to transpose this array such that rows become columns and columns become rows. Obviously I could do this in a double for-loop, but this seems massively inelegant and will be pretty slow. I was wondering if there's something clever in C++ or the STL that would let me swap the inner and outer vectors around quickly and efficiently, rather than writing...
for (int iRow = 0; iRow < nRows; ++iRow)
{
for (int iCol = 0; iCol < nCols; ++iCol)
{
myNew2DArray[iCol][iRow] = myOriginal2DArray[iRow][iCol];
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
或者,您可以将矩阵存储在向量中,并使用一个标志来指定矩阵是否转置。然后你只需计算指数即可。这是一个例子:
这将减少转置矩阵的成本,但会增加实际访问元素的成本。
Alternatively, you can store the matrix in a vector and have a flag that specifies whether the matrix is transposed or not. Then you simply calculate the index. Here is an example:
This will reduce the cost of transposing the matrix, but increases the cost of actually accessing the elements.
我的建议是创建一个名为 Matrix 的类,其中包含您正在讨论的矩阵。为该类提供一个函数
transpose()
,用于切换状态“转置”的状态标志。然后,重载 [] 运算符以遵循 mwd 在矩阵处于转置状态时反转索引的建议。My suggestion would be to make a class called
Matrix
that contains the matrix that you are talking about. Give the class a functiontranspose()
that toggles a state flag for the state "transposed". Then, overload the [] operator to follow mwd's suggestion of inverting the indeces when the matrix is in the transposed state.您已经编写的代码几乎是最简单的方法。实际上你不需要向量的向量。您只需将每个新“行”附加到单个向量即可。那么,当 n 是矩阵的“宽度”时,原始向量向量中的元素矩阵 [i][j] 现在是矩阵 [(i*n)+j]。最繁琐的部分是提出执行转置的算法。我并不是说这种方法更好,但它是一种替代方法,而且你已经得到的已经很好了。
What you've coded already is pretty much the easiest way. Really you don't need a vector of vectors. You can just append each new 'row' to a single vector. Then what would have been element matrix[i][j] in your original vector of vectors is now matrix[(i*n)+j], when n is the 'width' of your matrix. The fiddly part is coming up with the algorithm to perform the transpose. I'm not saying this way is any better, but it's an alternative route, and what you've got already is fine.
最好的选择是使用特征矩阵库,它将转置属性存储在矩阵类的参数中。如果这不是一个选择,请搜索众多矩阵转置算法之一。
Your best bet is using the Eigen matrix library, which stores the transposedness property in a parameter of the matrix class. If that is not an option, google for one of the numerous matrix transpose algorithms.