C ++ 2D column vector search

I have a 2D-vector: vector<vector<int>>. I use iterators to go through rows, but what's the best way to go through columns?

This is the code I use to iterate through the lines:

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

Regards, Milen Vichev

+4
source share
2 answers

I think the way to do this is through transposing 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 should change inside the body of the cycle, but it is SLOW.

You can get some rate of change transposeto return the "representation" of the matrix transpose:

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

In any case, even this solution is slower than accessing items through operator[].

, , 1D- (- fooobar.com/questions/685697/...).

+1

:

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

Source: https://habr.com/ru/post/1542616/


All Articles