简体   繁体   中英

C++ 2D vector search by column

I have 2D vector like this: 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

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:

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

Anyway even this solution is slower than accessing elements via 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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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