Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Array.h
- // Array
- //
- // Created by Kelvin Zhang on 8/9/16.
- // Copyright © 2016 Kelvin Zhang. All rights reserved.
- //
- #ifndef Array_h
- #define Array_h
- #include <stdlib.h>
- #include <stdio.h>
- template <class T>
- class Array
- {
- private:
- T *buffer;
- unsigned int length;
- unsigned int capacity;
- bool ensureCapacity()
- {
- if (length >= capacity)
- {
- unsigned int newCapacity = capacity * 2;
- void *tmp = realloc(buffer, newCapacity * sizeof(T));
- if (!tmp)
- {
- return false;
- }
- buffer = (T*)tmp;
- capacity = newCapacity;
- }
- return true;
- }
- public:
- Array()
- {
- capacity = 4;
- length = 0;
- buffer = (T*)malloc(capacity * sizeof(T));
- }
- Array(const Array &arr)
- {
- length = arr.length;
- capacity = arr.capacity;
- buffer = malloc(capacity);
- memcpy(buffer, arr.buffer, length);
- printf("Copy %p created from %p by const &arr()\n", buffer, arr.buffer);
- }
- Array(Array &&arr)
- {
- length = arr.length;
- capacity = arr.capacity;
- buffer = (T*)malloc(capacity);
- memcpy(buffer, arr.buffer, length);
- printf("Copy %p created from %p by Arr&&()\n", buffer, arr.buffer);
- }
- Array &operator=(const Array &arr)
- {
- length = arr.length;
- capacity = arr.capacity;
- buffer = (T*)malloc(arr.capacity);
- memcpy(buffer, arr.buffer, length);
- printf("Copy %p created from %p by operator=()\n", buffer, arr.buffer);
- return *this;
- }
- Array(unsigned int initialCapacity)
- {
- if(initialCapacity == 0)
- {
- initialCapacity = 4;
- }
- capacity = initialCapacity;
- length = 0;
- buffer = (T*)malloc(capacity * sizeof(T));
- printf("buffer: %p capacity: %d\n", buffer, capacity);
- }
- ~Array()
- {
- printf("deallocing %p\n", buffer);
- for(int i = 0; i < length; i ++)
- {
- buffer[i].~T();
- }
- free(buffer);
- }
- T *begin()
- {
- return buffer;
- }
- T* data()
- {
- return buffer;
- }
- T* end()
- {
- return buffer + length;
- }
- unsigned int size()
- {
- return length;
- }
- bool push_back(T &&t)
- {
- printf("Pass by r ref...\n");
- if(!ensureCapacity())
- {
- return false;
- }
- buffer[length] = t;
- length++;
- return true;
- }
- bool push_back(const T &t)
- {
- printf("Pass by l ref...\n");
- if(!ensureCapacity())
- {
- return false;
- }
- buffer[length] = t;
- length++;
- return true;
- }
- bool pop_back()
- {
- if (length)
- {
- length--;
- return buffer[length];
- }
- }
- T& operator[](int index)
- {
- return buffer[index];
- }
- void clear()
- {
- length = 0;
- }
- bool erase(int index)
- {
- if (index >= length || index < 0)
- {
- return false;
- }
- buffer[index].~T();
- for (int i = index + 1; i < length; i++)
- {
- buffer[i - 1] = buffer[i];
- }
- length--;
- }
- };
- #endif /* Array_h */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement