Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template<typename type> class Array {
- class ArrayProxy {
- Array* array;
- int index;
- public:
- ArrayProxy(Array* array, int index) {
- this->array = array;
- this->index = index;
- }
- type operator= (type value) { array->set(index, value); return array->get(index); }
- operator type() { return array->get(index); }
- };
- public:
- void set(unsigned int index, type value) {
- if (index > this->____size) {
- this->ensureAdditionalSize(this->____size - index);
- }
- this->____rawData[index] = value;
- if (index > this->____dataSize) {
- this->____dataSize = index + 1;
- }
- }
- type get(unsigned int index) {
- return this->____rawData[index];
- }
- unsigned int getSize() {
- return this->____dataSize;
- }
- void append(type value) {
- this->ensureAdditionalSize(32);
- this->____rawData[this->____dataSize] = value;
- this->____dataSize++;
- }
- ArrayProxy operator[] (unsigned int index) {
- return ArrayProxy(this, index);
- }
- ~Array() {
- if (this->____rawData != nullptr) {
- free(this->____rawData);
- this->____rawData = nullptr;
- }
- }
- private:
- type* ____rawData = nullptr;
- unsigned int ____size = 0;
- unsigned int ____dataSize = 0;
- void ensureAdditionalSize(unsigned int size) {
- if (this->____dataSize + size > this->____size) {
- if (this->____rawData != nullptr) {
- void* toFree = this->____rawData;
- unsigned int newSize = this->____size * ARRAY_INCREATE_FACTOR;
- MALLOC(this->____rawData, type, newSize);
- memset(this->____rawData, 0, newSize);
- memcpy(this->____rawData, toFree, this->____size * sizeof(type));
- this->____size = newSize;
- free(toFree);
- }
- else {
- unsigned int newSize = ARRAY_DEFAULT_SIZE;
- MALLOC(this->____rawData, type, newSize);
- memset(this->____rawData, 0, newSize);
- this->____size = newSize;
- this->____dataSize = 0;
- }
- this->ensureAdditionalSize(size);
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement