-
Notifications
You must be signed in to change notification settings - Fork 0
/
Vector.h
28 lines (26 loc) · 1.82 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
25
26
27
28
#ifndef VECTOR_H
#define VECTOR_H
/*
* Class copy from the arduino forum
* From: http://arduino.cc/forum/index.php/topic,45626.0.html
* Last modification: Guilherme D'Amoreira on June 2013
*/
// Minimal class to replace std::vector
template<typename Data> class Vector {
size_t d_size; // Stores no. of actually stored objects
size_t 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 add(Data const &x) { if (d_capacity == d_size) resize(); d_data[d_size++] = x; }; // Adds new value. If needed, allocates more space
void remove(size_t idx) { if (idx >= d_size) return; for (size_t i=idx; i<d_size; i++) d_data[i] = d_data[i+1]; d_size--;} //scoot everyone down by one
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