c++行和列矩阵的操作

C++ row and columns matrix manipulation

本文关键字:操作 c++      更新时间:2023-10-16

我创建了一个二维矩阵作为向量的向量:

vector<vector<int>> mat;

现在我需要交换矩阵的行和列,例如:

row 0 swapped with row 4 
column 5 swapped with column 1

行不是问题,因为有STL库的swap()函数。交换行似乎很有问题,因为,当然,它们不被视为一个原子结构。所以在这一点上我真的被困住了……我曾考虑过残忍地交换我感兴趣的行中的每个元素,但这似乎相当不优雅。你知道怎样才能实现我的目标吗?

如果您认为" elance "是一个可以为您做所有这些事情的STL函数,那么就没有这样的函数了。STL的目的并不是让你的代码尽可能的简单,c++的创建者只在STL中添加如下的东西:

  • 在当前语言的工具
  • 下很难实现
  • 需要编译器特殊支持的事情(特殊优化等)
  • 一些元素变得普遍

你自己实现。

如果你不想使用for (;;)循环,因为它在某些时候不是"优雅的",那么你可以这样做:

/* 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:如果速度对您很重要,并且您希望交换列和交换行一样快(在O(1)中),那么您可以使用这个实现(占用额外的空间):

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]);