-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabvector.hpp
More file actions
113 lines (89 loc) · 2.07 KB
/
abvector.hpp
File metadata and controls
113 lines (89 loc) · 2.07 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// vectors are lifeline of C++ programming,
// If we can't use the STL version, let's make our own version of it
/*
@Functionality: Basic vector class
@Author: Abhishek Singh
*/
#include <new>
#include <cassert>
#pragma once
/*
@ Public APIs implemented with this vector class
1). push_back
2). size
3). [] ==> for indexing
4). pop_back
5). clear
*/
template<class T>
class abvector
{
public:
abvector()
{
// STL vector takes the default preallocation size as 2 but
// I'd rather allocate enough memory rather than reallocating again and again
abAlloc(15);
}
~abvector()
{
clear();
::operator delete(data_, capacity_ * sizeof(T));
}
void abAlloc(size_t newCapacity)
{
T* newDataBlock = (T*)::operator new(newCapacity * sizeof(T));
for (size_t idx = 0; idx < size_; idx++)
{
newDataBlock[idx] = std::move(data_[idx]);
}
for (size_t idx = 0; idx < size_; idx++)
{
data_[idx].~T();
}
::operator delete(data_, capacity_ * sizeof(T));
data_ = newDataBlock;
capacity_ = newCapacity;
}
void push_back(const T& value)
{
if (size_ >= capacity_) abAlloc(2*capacity_);
data_[size_++] = value;
}
void push_back(T&& value)
{
if (size_ >= capacity_) abAlloc(2*capacity_);
data_[size_++] = std::move(value);
}
size_t size() const { return size_; }
const T& operator[](const size_t index) const
{
assert(index < size_);
return data_[index];
}
T& operator[](const size_t index)
{
assert(index < size_);
return data_[index];
}
void pop_back()
{
if (size_ > 0)
{
size_--;
data_[size_].~T();
}
}
void clear()
{
for (size_t idx = 0; idx < size_; idx++)
{
data_[idx].~T();
}
size_ = 0;
}
private:
T* data_ = nullptr; // pointer to array
size_t size_ = 0;
size_t capacity_ = 0;
};