Skip to content

Instantly share code, notes, and snippets.

@ziap
Last active November 12, 2022 02:25
Show Gist options
  • Select an option

  • Save ziap/c51a112371fcb06c455a6fee2d956f44 to your computer and use it in GitHub Desktop.

Select an option

Save ziap/c51a112371fcb06c455a6fee2d956f44 to your computer and use it in GitHub Desktop.
Simple C++ dynamic array implementation
#include <cstdlib>
#include <cstring>
template <typename T> class vec {
private:
static constexpr size_t INIT_CAP = 1;
size_t cap;
size_t count;
T *data;
public:
vec() {
cap = INIT_CAP;
count = 0;
data = (T *)malloc(cap * sizeof(T));
}
template <class... Ts> vec(Ts... xs) {
cap = INIT_CAP;
count = sizeof...(Ts);
while (cap < count)
cap *= 2;
T init[] = {xs...};
data = (T *)malloc(cap * sizeof(T));
memcpy(data, init, count * sizeof(T));
}
~vec() { free(data); }
size_t size() { return count; }
void push(T item) {
if (count >= cap) {
cap *= 2;
data = (T *)realloc(data, cap * sizeof(T));
}
data[count++] = item;
}
T pop() { return data[--count]; }
T &operator[](size_t idx) { return *(data + idx); }
T *begin() { return data; }
T *end() { return data + count; }
const T *cbegin() { return (const T *)data; }
const T *cend() { return (const T *)(data + count); }
};
// USAGE
#include <cstdio>
#include <vec.h>
int main() {
vec<int> a = {1, 2, 3, 5};
for (auto i = 0; i < 5; i++)
a.push(i * i);
for (auto i : a)
printf("%d\n", i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment