稀疏矩阵的创建和计算 C++代码
时间: 2024-03-09 09:50:21 浏览: 12
以下是一个稀疏矩阵的创建和计算C++代码示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
class SparseMatrix {
private:
vector<vector<int>> matrix;
int rows, cols;
public:
SparseMatrix(int row, int col) {
rows = row;
cols = col;
}
// 添加一个元素
void insert(int row, int col, int val) {
if (row >= rows || col >= cols) {
throw "Invalid index";
}
if (val != 0) {
matrix.push_back({row, col, val});
}
}
// 获取一个元素
int get(int row, int col) {
for (auto& item : matrix) {
if (item[0] == row && item[1] == col) {
return item[2];
}
}
return 0;
}
// 矩阵加法
SparseMatrix operator+(SparseMatrix& other) {
if (rows != other.rows || cols != other.cols) {
throw "Invalid matrix size";
}
SparseMatrix result(rows, cols);
int i = 0, j = 0;
while (i < matrix.size() && j < other.matrix.size()) {
if (matrix[i][0] == other.matrix[j][0] && matrix[i][1] == other.matrix[j][1]) {
int val = matrix[i][2] + other.matrix[j][2];
result.insert(matrix[i][0], matrix[i][1], val);
i++;
j++;
} else if (matrix[i][0] < other.matrix[j][0] || (matrix[i][0] == other.matrix[j][0] && matrix[i][1] < other.matrix[j][1])) {
result.insert(matrix[i][0], matrix[i][1], matrix[i][2]);
i++;
} else {
result.insert(other.matrix[j][0], other.matrix[j][1], other.matrix[j][2]);
j++;
}
}
while (i < matrix.size()) {
result.insert(matrix[i][0], matrix[i][1], matrix[i][2]);
i++;
}
while (j < other.matrix.size()) {
result.insert(other.matrix[j][0], other.matrix[j][1], other.matrix[j][2]);
j++;
}
return result;
}
// 打印矩阵
void print() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << get(i, j) << " ";
}
cout << endl;
}
}
};
int main() {
SparseMatrix m1(3, 3);
m1.insert(0, 0, 1);
m1.insert(0, 2, 2);
m1.insert(1, 1, 3);
m1.insert(2, 0, 4);
m1.insert(2, 2, 5);
SparseMatrix m2(3, 3);
m2.insert(0, 1, 1);
m2.insert(1, 1, 2);
m2.insert(1, 2, 3);
m2.insert(2, 0, 4);
m2.insert(2, 2, 5);
SparseMatrix m3 = m1 + m2;
m1.print();
cout << endl;
m2.print();
cout << endl;
m3.print();
return 0;
}
```
在这个示例中,我们添加了一个矩阵加法的操作符重载。其中,我们使用了类似于归并排序的方法将两个稀疏矩阵合并成一个新的稀疏矩阵。另外,我们也添加了打印矩阵的功能。