-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathVector.cpp
More file actions
79 lines (63 loc) · 2.01 KB
/
Vector.cpp
File metadata and controls
79 lines (63 loc) · 2.01 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#pragma once
#include <vector>
#include <random>
class Vector {
private:
// We store our data in a contiguous block of memory for cache efficiency
std::vector<float> data_;
public:
Vector() : data_() {}
// Constructor that creates a vector of gizen size
explicit Vector(size_t size) : data_(size, 0.0f) {};
// Constructor that creates a vector from existing data
Vector(const std::vector<float>& data) : data_(data) {}
// Copy constructor
Vector(const Vector& other) : data_(other.data_) {}
// Assignment operator
Vector& operator=(const Vector& other) {
if (this != &other) {
data_ = other.data_;
}
return *this;
}
// Access elements (both const and non-const version)
float& operator[](size_t index) {
return data_[index];
}
const float& operator[](size_t index) const {
return data_[index];
}
// Basic vector operations we will need
Vector& operator+=(const Vector& other){
if (other.size() != size()) {
throw std::invalid_argument("Vector dimensions don't match for addition");
}
for (size_t i = 0; i < size(); ++i){
data_[i] += other[i];
}
return *this;
}
// Element-wise multiplication (Hadamard product) - will be needed for backpropogation
Vector hadamard(const Vector& other) const {
if (other.size() != size()) {
throw std::invalid_argument("Vector dimensions don't match for Hadamard product");
}
Vector result(size());
for (size_t i = 0; i < size(); ++i){
result[i] = data_[i] * other[i];
}
return result;
}
void uniform_init() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float> dis(-0.1f, 0.1f);
for (size_t i = 0; i < size(); ++i) {
data_[i] = dis(gen);
}
}
// Size accessor
size_t size() const {
return data_.size();
}
};