-
Notifications
You must be signed in to change notification settings - Fork 0
/
DynamicArray.go
55 lines (45 loc) · 1.06 KB
/
DynamicArray.go
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
package dynamic_array
// A resizable array.
//
// Equivalent to a slice.
type DynamicArray[T any] []T
func New[T any]() DynamicArray[T] {
return DynamicArray[T]{}
}
// Return the number of element.
func (d *DynamicArray[T]) Len() int {
return len(*d)
}
// Return the capacity.
func (d *DynamicArray[T]) Cap() int {
return cap(*d)
}
// Return a pointer to the first element.
func (d *DynamicArray[T]) Front() *T {
return &(*d)[0]
}
// Return a pointer to the last element.
func (d *DynamicArray[T]) Back() *T {
return &(*d)[len(*d)-1]
}
// Append e to the array.
func (d *DynamicArray[T]) PushBack(e T) {
*d = append(*d, e)
}
// Remove the last element.
//
// It also zero it for the GC to clean up.
func (d *DynamicArray[T]) PopBack() {
last := len(*d) - 1
var zero T
(*d)[last] = zero
*d = (*d)[:last]
}
// Return an iterator points to the first element.
func (d *DynamicArray[T]) Begin() Iterator[T] {
return Iterator[T]{d, 0}
}
// Return an iterator one pass the last element.
func (d *DynamicArray[T]) End() Iterator[T] {
return Iterator[T]{d, len(*d)}
}