Skip to content
This repository has been archived by the owner on Apr 6, 2024. It is now read-only.

collections/vector: implement dynamic table described in CLRS #2

Merged
merged 17 commits into from
Aug 7, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/bazel-*
.idea
51 changes: 42 additions & 9 deletions src/collections/vector.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,18 @@ class Vec {
private:
T* buf;
size_t len;
size_t cap;
iosmanthus marked this conversation as resolved.
Show resolved Hide resolved

public:
// Get the length of the vector
size_t size();

// Get the size of underneath array
size_t capacity();

// Set the size of underneath array
size_t capacity(size_t s);
iosmanthus marked this conversation as resolved.
Show resolved Hide resolved

// Examine if the vector is empty.
bool is_empty();

Expand All @@ -36,6 +43,7 @@ inline Vec<T>::Vec()
{
this->buf = nullptr;
len = 0;
iosmanthus marked this conversation as resolved.
Show resolved Hide resolved
cap = 0;
}

template <typename T>
Expand All @@ -44,6 +52,23 @@ inline size_t Vec<T>::size()
return this->len;
}

template<typename T>
inline size_t Vec<T>::capacity()
{
return this->cap;
}

template<typename T>
inline size_t Vec<T>::capacity(size_t s)
iosmanthus marked this conversation as resolved.
Show resolved Hide resolved
{
if (s >= this->len) {
T *new_buf = new T[s];
this->cap = s;
std::copy(this->buf, this->buf+this->len, new_buf);
}
return this->cap;
}

template <typename T>
inline Vec<T>::~Vec()
{
Expand All @@ -60,21 +85,29 @@ inline bool Vec<T>::is_empty()
template <typename T>
void Vec<T>::push(T data)
{
T* new_buf = new T[this->len + 1];
std::copy(this->buf, this->buf + this->len, new_buf);
new_buf[this->len] = data;

delete[] this->buf;

this->buf = new_buf;
size_t total = this->len+1;
if (total > this->cap) {
size_t new_cap = total*3/2 + 1;
T *new_buf = new T[new_cap];
this->cap = new_cap;
std::copy(this->buf, this->buf + this->len, new_buf);
delete[] this->buf;
this->buf = new_buf;
}
buf[this->len]= data;
iosmanthus marked this conversation as resolved.
Show resolved Hide resolved
this->len++;

}

template <typename T>
std::optional<T> Vec<T>::pop()
{
if (this->len > 0)
return this->buf[this->len-- - 1];
if (this->len > 0) {
fengkx marked this conversation as resolved.
Show resolved Hide resolved
if ((this->cap / this->len) > 2) {
capacity((this->len-1)*3/2);
}
return this->buf[this->len-- -1];
}

return {};
}
Expand Down