-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathOrderedVector.hpp
51 lines (44 loc) · 1.2 KB
/
OrderedVector.hpp
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
#include <memory>
#include <stdexcept>
template<typename ElementType>
class OrderedVector {
public:
OrderedVector(unsigned int maxLen)
: m_maxLen(maxLen), m_data(std::make_unique<ElementType[]>(m_maxLen)) { }
OrderedVector(const OrderedVector&) = delete;
OrderedVector& operator=(const OrderedVector&) = delete;
bool add(ElementType value);
ElementType& at(unsigned int n) {
if (n >= m_len) {
throw std::out_of_range("too big");
}
return m_data[n];
}
ElementType& operator[](unsigned int n) {
return at(n);
}
private:
unsigned int m_len = 0;
unsigned int m_maxLen;
std::unique_ptr<ElementType[]> m_data;
};
template<typename ElementType>
bool OrderedVector<ElementType>::add(ElementType value) {
if (m_len >= m_maxLen) {
return false;
}
// find insertion point
unsigned int insertIndex = 0;
while (insertIndex < m_len && m_data[insertIndex] < value)
insertIndex++;
// move end of vector
unsigned int index = m_len;
while (index > insertIndex) {
m_data[index] = m_data[index-1];
index--;
}
// actual insertion
m_data[index] = value;
m_len++;
return true;
}