-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathrowwisematrix.cpp
83 lines (71 loc) · 1.92 KB
/
rowwisematrix.cpp
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "rowwisematrix.h"
#include <cstddef>
#include <iostream>
RowWiseMatrix::RowWiseMatrix(unsigned long int numberOfRows) : matrix(numberOfRows, NULL)
{
for (unsigned long int i = 0; i < numberOfRows; i++)
matrix[i] = new row;
}
RowWiseMatrix::~RowWiseMatrix()
{
for (unsigned long int i = 0; i < n(); i++)
delete matrix[i];
}
void RowWiseMatrix::Clear(unsigned long int numberOfRows)
{
for (unsigned long int i = 0; i < n(); i++)
delete matrix[i];
matrix = std::vector<row*>(numberOfRows, NULL);
for (unsigned long int i = 0; i < numberOfRows; i++)
matrix[i] = new row;
}
RowWiseMatrix::row* RowWiseMatrix::GetRow(unsigned long int id)
{
if (id < n())
return matrix[id];
else return NULL;
}
double RowWiseMatrix::Get(unsigned long int i, unsigned long int j)
{
// if i outside of range return 0
if (i >= n())
return 0;
// look for j entry in ith row
for (unsigned long int it = 0; it < matrix[i]->size(); it++)
if ((*matrix[i])[it].id == j)
return (*matrix[i])[it].value;
// If entry wasn't found return 0
return 0;
}
unsigned long int RowWiseMatrix::n()
{
return matrix.size();
}
// Set entry (i,j) to value, return true if new entry was created, false if existing entry was modified
bool RowWiseMatrix::SetEntry(unsigned long int i, unsigned long int j, double value)
{
// First step: expand matrix if needed
if (i >= n())
{
unsigned long int missing_rows = i - n() + 1;
for (unsigned long int it = 0; it < missing_rows; it++)
matrix.push_back(new row);
}
// Second step: set entry
for (unsigned long int it = 0; it < matrix[i]->size(); it++)
{
if ((*matrix[i])[it].id == j)
{
if (value == 0)
matrix[i]->erase(matrix[i]->begin() + it);
else (*matrix[i])[it].value = value;
return false;
}
}
if (value != 0)
{
entry newEntry = {j, value};
matrix[i]->push_back(newEntry);
}
return true;
}