This repository was archived by the owner on Feb 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSparse_Matrix.cpp
More file actions
46 lines (46 loc) · 1.3 KB
/
Copy pathSparse_Matrix.cpp
File metadata and controls
46 lines (46 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <vector>
class SparseMatrix {
private:
struct Element {
int row;
int col;
int value;
Element(int r, int c, int v) : row(r), col(c), value(v) {}
};
int numRows;
int numCols;
std::vector<Element> elements;
public:
SparseMatrix(int rows, int cols) : numRows(rows), numCols(cols) {}
void insert(int row, int col, int value) {
if (row < 0 || row >= numRows || col < 0 || col >= numCols) {
std::cerr << "Error: Index out of bounds\n";
return;
}
if (value != 0) {
elements.push_back(Element(row, col, value));
}
}
void printMatrix() const {
std::vector<std::vector<int>> matrix(numRows, std::vector<int>(numCols, 0));
for (const Element& element : elements) {
matrix[element.row][element.col] = element.value;
}
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < numCols; ++j) {
std::cout << matrix[i][j] << " ";
}
std::cout << "\n";
}
}
};
int main() {
SparseMatrix sparseMat(5, 5);
sparseMat.insert(0, 1, 2);
sparseMat.insert(1, 2, 3);
sparseMat.insert(2, 3, 4);
sparseMat.insert(3, 4, 5);
sparseMat.printMatrix();
return 0;
}