使用链表转换稀疏矩阵(遍历问题)
Transposing a sparse matrix using linked lists (Traversal problems)
我正试图在c++中转置一个稀疏矩阵。我正在努力遍历新的转置矩阵。我想输入从矩阵的第一行到新矩阵的第一列的所有内容。
每一行都有数字应该在其中的列索引和数字本身。
输入:
colInd num
输入:
1 1 2 2 3 3
1 4 2 5 3 6
1 7 2 8 3 9
输出:
1 1 2 4 3 7
1 2 5 3 8
1 3 2 6 3 9
如何使列表遍历第一列,插入第一个元素,然后返回顶部,插入第二列。如果这是两个很难遵循的问题,请道歉。但我所想帮助的是在正确的时间将转置矩阵遍历到正确的位置,在正确的位置插入一个nz(非零)对象。
这是我的代码
list<singleRow> tran;
//Finshed reading so transpose
for (int i = 0; i < rows.size(); i++){ // Initialize transposed matrix
singleRow trow;
tran.push_back(trow);
}
list<singleRow>::const_iterator rit;
list<singleRow>::const_iterator trowit;
int rowind;
for (rit = rows.begin(), rowind = 1; rit != rows.end(); rit++, rowind++){//rit = row iterator
singleRow row = *rit;
singleRow::const_iterator nzit;
trowit = tran.begin(); //Start at the beginning of the list of rows
trow = *trowit;
for (nzit = row.begin(); nzit != row.end(); nzit++){//nzit = non zero iterator
int col = nzit->getCol();
double val = nzit->getVal();
trow.push_back(nz(rowind,val)); //How do I attach this to tran so that it goes in the right place?
trowit++;
}
}
您对矩阵的表示效率低下:它没有使用矩阵稀疏的事实。我这么说是因为它包括矩阵的所有行,即使它们中的大多数是零(空),就像稀疏矩阵通常发生的那样。
你的代表也很难共事。因此,我建议先转换表示(到一个规则的2-D数组),转换矩阵,然后再转换回来。
(编辑时间:)或者,您可以更改表示,例如,如下所示:
输入:rowInd colInd num
1 1 1
1 2 2
1 2 3
2 1 4
2 2 5
2 3 6
3 1 7
3 2 8
3 3 9
输出:
1 1 1
2 1 2
3 1 3
1 2 4
2 2 5
3 2 6
1 3 7
2 3 8
3 3 9
代码应该是这样的:
struct singleElement {int row, col; double val;};
list<singleElement> matrix_input, matrix_output;
...
// Read input matrix from file or some such
list<singleElement>::const_iterator i;
for (i = matrix_input.begin(); i != matrix_input.end(); ++i)
{
singleElement e = *i;
std::swap(e.row, e.col);
matrix_output.push_back(e);
}
稀疏矩阵的列表表示的选择不适合换位。有时,在考虑算法和数据结构时,最好的做法是承担将数据结构转换为更适合算法的数据结构的风险,而不是破坏算法以使用错误的数据结构。
在这种情况下,例如,你可以将矩阵读取到坐标列表表示中,这将非常容易转换,然后写入你喜欢的任何表示中。如果空间是一个挑战,那么您可能需要逐个块地执行此操作,在目标表示中按1分配新列,并在执行过程中释放旧表示中的列。
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 在使用 In Order 遍历成员函数时引发异常(堆栈溢出)时出现问题
- 循环遍历向量<string>并保持每个元素"count"时出现问题
- 如何修复关卡顺序遍历问题(二叉树)的无限循环错误
- 如果使用迭代器,如何解决遍历列表的问题
- 遍历 QHash 并提取重复值的键时遇到问题
- 遍历目录递归问题
- 指针问题C++,未正确遍历
- 使用链表转换稀疏矩阵(遍历问题)
- 线程内二叉树的插入或顺序遍历有什么问题
- 遍历类向量导致问题
- 遍历C++中的字符串列表,出了什么问题?
- 图形遍历问题