用visual C++写代码:使用特殊矩阵的压缩存储,存储 1 2 3 4 , 0 5 6 7 , 0 0 8 9 , 0 0 0 10三角矩阵
时间: 2024-01-11 17:02:58 浏览: 39
以下是使用特殊矩阵的压缩存储,存储给定的三角矩阵的示例代码:
```c++
#include <iostream>
using namespace std;
const int MAX_SIZE = 10;
class SparseMatrix {
private:
int matrix[MAX_SIZE][MAX_SIZE];
int size;
public:
SparseMatrix(int arr[][MAX_SIZE], int n) {
size = n;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
matrix[i][j] = arr[i][j];
}
}
}
void display() {
cout << "Matrix:\n";
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void compress() {
int count = 0;
int compressed[MAX_SIZE*(MAX_SIZE+1)/2][3];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (matrix[i][j] != 0) {
compressed[count][0] = i;
compressed[count][1] = j;
compressed[count][2] = matrix[i][j];
count++;
}
}
}
cout << "Compressed Matrix:\n";
for (int i = 0; i < count; i++) {
for (int j = 0; j < 3; j++) {
cout << compressed[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
};
int main() {
int arr[MAX_SIZE][MAX_SIZE] = {
{1, 2, 3, 4},
{0, 5, 6, 7},
{0, 0, 8, 9},
{0, 0, 0, 10}
};
SparseMatrix sm(arr, 4);
sm.display();
sm.compress();
return 0;
}
```
输出:
```
Matrix:
1 2 3 4
0 5 6 7
0 0 8 9
0 0 0 10
Compressed Matrix:
0 0 1
0 1 2
0 2 3
0 3 4
1 1 5
1 2 6
1 3 7
2 2 8
2 3 9
3 3 10
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)