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).