实现该稀疏矩阵的压缩存储
时间: 2024-06-14 16:04:38 浏览: 153
以下是C++实现稀疏矩阵的压缩存储的代码示例:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 定义稀疏矩阵的三元组结构
struct Triplet {
int row; // 行号
int col; // 列号
int value; // 值
};
// 压缩存储稀疏矩阵
void compressSparseMatrix(vector<vector<int>>& matrix, vector<Triplet>& compressedMatrix) {
int rows = matrix.size();
int cols = matrix[0].size();
// 遍历原矩阵,将非零元素存储到三元组中
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] != 0) {
Triplet triplet;
triplet.row = i;
triplet.col = j;
triplet.value = matrix[i][j];
compressedMatrix.push_back(triplet);
}
}
}
}
int main() {
// 原矩阵
vector<vector<int>> matrix = {{0, 0, 0, 0},
{0, 5, 0, 0},
{0, 0, 0, 0},
{0, 0, 3, 0},
{0, 0, 0, 0}};
// 压缩存储后的稀疏矩阵
vector<Triplet> compressedMatrix;
// 压缩存储稀疏矩阵
compressSparseMatrix(matrix, compressedMatrix);
// 输出压缩存储后的稀疏矩阵
for (int i = 0; i < compressedMatrix.size(); i++) {
cout << "row: " << compressedMatrix[i].row << ", col: " << compressedMatrix[i].col << ", value: " << compressedMatrix[i].value << endl;
}
return 0;
}
```
阅读全文