-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.h
24 lines (22 loc) · 1.54 KB
/
vector.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#ifndef VECTOR_H
#define VECTOR_H
#include <Arduino.h>
// Minimal class to replace std::vector
template<typename Data>
class Vector {
byte d_size; // Stores no. of actually stored objects
byte d_capacity; // Stores allocated capacity
Data *d_data; // Stores data
public:
Vector() : d_size(0), d_capacity(0), d_data(0) {}; // Default constructor
//Vector(Vector const &other) : d_size(other.d_size), d_capacity(other.d_capacity), d_data(0) { d_data = (Data *)malloc(d_capacity*sizeof(Data)); memcpy(d_data, other.d_data, d_size*sizeof(Data)); }; // Copy constuctor
//~Vector() { free(d_data); }; // Destructor
//Vector &operator=(Vector const &other) { free(d_data); d_size = other.d_size; d_capacity = other.d_capacity; d_data = (Data *)malloc(d_capacity*sizeof(Data)); memcpy(d_data, other.d_data, d_size*sizeof(Data)); return *this; }; // Needed for memory management
void push_back(Data const &x) { if (d_capacity == d_size) resize(); d_data[d_size++] = x; }; // Adds new value. If needed, allocates more space
//size_t size() const { return d_size; }; // Size getter
//Data const &operator[](size_t idx) const { return d_data[idx]; }; // Const getter
Data &operator[](size_t idx) { return d_data[idx]; }; // Changeable getter
private:
void resize() { d_capacity = d_capacity ? d_capacity*2 : 1; Data *newdata = (Data *)malloc(d_capacity*sizeof(Data)); memcpy(newdata, d_data, d_size * sizeof(Data)); free(d_data); d_data = newdata; };// Allocates double the old space
};
#endif // VECTOR_H