-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtensor.cpp
More file actions
61 lines (51 loc) · 1.64 KB
/
tensor.cpp
File metadata and controls
61 lines (51 loc) · 1.64 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include "tensor.hpp"
#include <print>
#include <utility>
namespace partdiff {
tensor::tensor(std::size_t num_matrices, std::size_t num_rows, std::size_t num_cols)
: num_matrices(num_matrices),
num_rows(num_rows),
num_cols(num_cols) {
auto size = num_matrices * num_rows * num_cols;
try {
data = new double[size];
} catch (std::bad_alloc &) {
auto size_bytes = size * sizeof(double);
std::println("Memory failure! (Requested {} bytes)", size_bytes);
exit(EXIT_FAILURE);
}
}
tensor::tensor(const tensor &other)
: num_matrices(other.num_matrices),
num_rows(other.num_rows),
num_cols(other.num_cols),
data(other.data) {}
tensor::tensor(tensor &&other) noexcept
: num_matrices(other.num_matrices),
num_rows(other.num_rows),
num_cols(other.num_cols),
data(std::exchange(other.data, nullptr)) {}
tensor &tensor::operator=(const tensor &other) {
return *this = tensor(other);
}
tensor &tensor::operator=(tensor &&other) noexcept // move assignment
{
std::swap(data, other.data);
num_matrices = other.num_matrices;
num_cols = other.num_cols;
num_rows = other.num_rows;
return *this;
}
tensor::~tensor() {
if (data) {
delete[] data;
data = nullptr;
}
}
double &tensor::operator[](std::size_t matrix, std::size_t row, std::size_t col) {
return data[(num_cols * num_rows * matrix) + (num_cols * row) + (col)];
}
double tensor::operator[](std::size_t matrix, std::size_t row, std::size_t col) const {
return data[(num_cols * num_rows * matrix) + (num_cols * row) + (col)];
}
} // namespace partdiff