Reputation: 722
I've created a 2D matrix as a vector of vectors like this :
vector<vector<int>> mat;
now I need to swap the row and columns of my matrix for example :
row 0 swapped with row 4
column 5 swapped with column 1
the rows aren't a problem since there is the swap() function of the stl library. Exchanging rows though seems quite problematic because, of course, they are not considered as one atomic structure. so at this point I'm really stuck... I've considered doing it brutally swapping every element of the rows I'm interested in, but it seems quite inelegant. Any idea of how I could achieve my goal ?
Upvotes: 0
Views: 1826
Reputation: 10400
If you consider "elenance" as a STL function that can do all this stuff for you, then there's no function like this. The aim of STL is not about making your code as simple as possible, the creators of C++ only add to STL things that:
So, just implement by your own.
If you don't want to use for (;;)
loops because it's not "elegant" at some point, then you can do something like this:
/* swapping column i and j */
std::vector<std::vector<T>> mat;
std::for_each(mat.begin(), mat.end(), [i,j](std::vector<int>& a)
{ std::swap(a[i], a[j]); });
Update: If the speed is important for you and you want to swap columns as fast as swapping rows (in O(1) ), then you can use this implementation (that takes extra space)):
std::vector<std::vector<int>> mat;
/* preprocessing */
std::vector<int> permutation(mat[0].size());
std::iota(permutation.begin(), permutation.end(), 0);
/* now, if you need to get the element mat[i][j] */
mat_i_j = mat[i][ permutation[j] ];
/* if you want to swap column i and j */
std::swap(permutation[i], permutation[j]);
Upvotes: 1