Y_Array

Run Settings
LanguageC++
Language Version
Run Command
#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <initializer_list> template<typename T> struct Y_Array { size_t count; size_t capacity; T *elem; Y_Array(std::initializer_list<T> list) { count = list.size(); capacity = count; elem = 0; if (count == 0) return; elem = (T *)calloc(capacity * sizeof(T), 1); size_t i = 0; for(T e : list) { elem[i] = e; i += 1; } } void add(T v) { if (elem == 0) { capacity = 4; elem = (T *)calloc(capacity * sizeof(T), 1); } else if(count >= capacity) { size_t new_capacity = capacity * 2; T *new_elem = (T *)calloc(new_capacity * sizeof(T), 1); memmove(new_elem, elem, capacity * sizeof(T)); free(elem); elem = new_elem; capacity = new_capacity; } elem[count] = v; count += 1; } T& operator [](intptr_t i) { assert(i >= 0 && "index is negative"); assert(i < count && "index is out of range"); return elem[i]; } void release() { free(elem); elem = 0; count = 0; capacity = 0; } }; int main() { Y_Array<int> a = {}; a.add(5); a.add(6); printf("[0] %i\n", a[0]); printf("[1] %i\n", a[1]); printf("count %zu\n", a.count); printf("capacity %zu\n", a.capacity); a.release(); return 0; }
Editor Settings
Theme
Key bindings
Full width
Lines