简体   繁体   English

C ++ 2D矢量按列搜索

[英]C++ 2D vector search by column

I have 2D vector like this: vector<vector<int>> . 我有像这样的2D矢量: vector<vector<int>> I am using iterators to go through it by rows BUT what would be the best practice to go through it by columns? 我正在使用迭代器按行遍历它但是按列进行检查的最佳做法是什么?

This is the code I use for iterating by rows: 这是我用于按行迭代的代码:

vector<vector<int>> vMatrix (4, vector<int>(4));
vector<vector<int>>::iterator itRow;
vector<int>::iterator itCol;

for (itRow = vMatrix.begin(); itRow != vMatrix.end(); itRow++)
{
    for (itCol = itRow->begin(); itCol != itRow->end(); itCol++) 
    {
        // do some stuff
    }
}

Kind regards, Milen Vichev 亲切的问候,Milen Vichev

Possible solution in this case: 这种情况下可能的解决方案

for (int col = 0; col < 4; col++)
{
    for (int row = 0; row < 4; row++) 
    {
        // do some stuff
    }
}

I think a way of doing that is through the transpose of the matrix: 我认为这样做的一种方法是通过矩阵的转置:

std::vector<std::vector<int>> transpose(const std::vector<std::vector<int>> &m)
{
  using std::vector;

  vector<vector<int>> result(m[0].size(), vector<int>(m.size()));

  for (vector<int>::size_type i(0); i < m[0].size(); ++i)
    for (vector<int>::size_type j(0); j < m.size(); ++j)
      result[i][j] = m[j][i];

  return result;
}

and

std::vector<std::vector<int>>::iterator itCol;
std::vector<int>::iterator itRow;
std::vector<std::vector<int>> t(transpose(vMatrix));

for (itRow = t.begin(); itRow != t.end(); itRow++)
  for (itCol = itRow->begin(); itCol != itRow->end(); itCol++)
  {
    // ...
  }

Nothing needs to change inside the loop body, but it's SLOW. 循环体内没有什么需要改变,但它是缓慢的。

You could gain some speed modifying transpose to return a "view" of the transpose of the matrix: 您可以获得一些速度修改transpose以返回矩阵转置的“视图”:

std::vector<std::vector<int *>> transpose(const std::vector<std::vector<int>> &)

Anyway even this solution is slower than accessing elements via operator[] . 无论如何,即使这个解决方案比通过operator[]访问元素慢。

Probably, if code refactoring is an option, a good solution would be to change from a vector of vectors to a 1D vector for better code locality (something like https://stackoverflow.com/a/15799557/3235496 ). 可能,如果代码重构是一个选项,一个好的解决方案是从向量向量更改为1D向量以获得更好的代码局部性(类似于https://stackoverflow.com/a/15799557/3235496 )。

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

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