c++行和列矩阵的操作
C++ row and columns matrix manipulation
我创建了一个二维矩阵作为向量的向量:
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]);
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- 为什么一个向量上的多线程操作很慢
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 位移操作和位掩码未检测到重复字符
- 如何进行特定的位操作?
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 字符串操作 - 字符计数
- 此代码中的操作流程是什么?C/C++.
- 复制和交换习惯用法与移动操作之间的交互
- 像union_这样的 Boost.Geometry 操作如何处理浮点类型的基本不精确性?
- 为什么 std::lerp 不适用于任何已实现所需操作的类型?
- 无法合并生成操作.. 先决条件不同