Quick actions

cmd+k|ctrl+k

Navigation

Languages

Y_Array

Snippet info

Language

Cpp

Visibility

public

Author

evine

Created

2021-03-05T15:49:33.92731Z

Updated

2021-03-07T17:50:03.471346Z

#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;
}
INFO