You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
package container
|
|
|
|
type Vector[T any] []T
|
|
|
|
// PushBack adds an element to the end of the vector.
|
|
// Complexity O(1) + array extesnion
|
|
func (v *Vector[T]) PushBack(e T) {
|
|
*v = append(*v, e)
|
|
}
|
|
|
|
// PopBack removes and returns the last element from the vector.
|
|
// If the vector is empty, it will panic.
|
|
// Complexity O(1)
|
|
func (v *Vector[T]) PopBack() T {
|
|
if !v.HasElement() {
|
|
panic("called PopBack() on an empty vector")
|
|
}
|
|
|
|
value := (*v)[len(*v)-1]
|
|
*v = (*v)[0 : len(*v)-1]
|
|
return value
|
|
}
|
|
|
|
// Len returns the length of the vector.
|
|
// It returns an integer representing the number of elements in the vector.
|
|
func (v Vector[T]) Len() int {
|
|
return len(v)
|
|
}
|
|
|
|
// HasElement returns true if the vector v contains at least one element.
|
|
func (v Vector[T]) HasElement() bool {
|
|
return v.Len() > 0
|
|
}
|
|
|
|
// PushFront adds an element to the front of the vector.
|
|
// Complexity O(n)
|
|
func (v *Vector[T]) PushFront(e T) {
|
|
newVect := make([]T, v.Len()+1)
|
|
copy(newVect[1:], *v)
|
|
newVect[0] = e
|
|
*v = newVect
|
|
}
|
|
|
|
// PopFront removes and returns the element at the front of the vector.
|
|
// It panics if the vector is empty.
|
|
// Complexity O(1)
|
|
func (v *Vector[T]) PopFront() T {
|
|
if !v.HasElement() {
|
|
panic("called PopFront() on an empty vector")
|
|
}
|
|
|
|
value := (*v)[0]
|
|
var zeroValue T
|
|
(*v)[0] = zeroValue
|
|
*v = (*v)[1:]
|
|
|
|
return value
|
|
}
|