forked from apanangadan/CSUF-CPSC_131
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathFixedVector.h
More file actions
57 lines (44 loc) · 1.17 KB
/
FixedVector.h
File metadata and controls
57 lines (44 loc) · 1.17 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
#pragma once
#include <stdexcept>
using namespace std;
template <typename ELT>
class FixedVector {
private:
int _length;
ELT *_array;
public:
// length copies of default_value
FixedVector(int length) {
if (length < 0) throw invalid_argument("length < 0");
_length = length;
_array = new ELT[_length];
}
// default constructor: empty vector
FixedVector() {
_length = 0;
_array = new ELT[0];
}
// copy constructor
FixedVector(const FixedVector& a) {
_length = a._length;
_array = new ELT[_length];
for (int i = 0; i < _length; i++)
_array[i] = a._array[i];
}
~FixedVector() { delete[] _array; }
int length() { return _length; }
bool is_empty() { return (_length == 0); }
ELT& get(int index) {
if ((index < 0) || (index >= _length)) throw range_error("index out of bounds");
return _array[index];
}
void set(int index, ELT value) {
if (is_empty()) throw invalid_argument("array is empty");
if ((index < 0) || (index >= _length)) throw range_error("index out of bounds");
_array[index] = value;
}
ELT& operator[](int index) {
if ((index < 0) || (index >= _length)) throw range_error("index out of bounds");
return get(index);
}
};