Last active
September 28, 2020 21:19
-
-
Save BenMcLean/bc168e513ff06d116c51e52a725d00b5 to your computer and use it in GitHub Desktop.
Simple data structure that encapsulates an array in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
template <class T> | |
class lolwut // a lolwut is a simple encapsulated array | |
{ | |
public: | |
lolwut() : data(NULL), size(0) | |
{ | |
} | |
~lolwut() | |
{ | |
clear(); | |
} | |
void clear() | |
{ | |
delete[] data; | |
data = NULL; | |
size = 0; | |
} | |
lolwut(const unsigned int arrSize) | |
{ | |
data = new T[size = arrSize]; | |
} | |
lolwut(const lolwut &other) : data(NULL) | |
{ | |
*this = other; | |
} | |
T &operator[](unsigned int idx) | |
{ | |
return data[idx]; | |
} | |
const T &operator[](unsigned int idx) const | |
{ | |
return data[idx]; | |
} | |
int getSize() const | |
{ | |
return size; | |
} | |
const lolwut &operator=(const lolwut &rhs) | |
{ | |
if (this != &rhs) // 1. avoid self-assignment (A=A) | |
{ | |
clear(); // 2. Delete dynamic data if any. | |
size = rhs.size; // 3. Copy static data. | |
data = new T[size]; // 4. Copy dynamic data if any. | |
for (unsigned int x = 0; x < size; ++x) | |
data[x] = rhs[x]; | |
} | |
return *this; | |
} | |
void clearResize(const unsigned int arrSize) | |
{ | |
clear(); | |
data = new T[size = arrSize]; | |
} | |
void resize(const unsigned int arrSize) | |
{ | |
T *newData = new T[arrSize]; | |
unsigned int copySize = arrSize; | |
if (size < arrSize) copySize = size; | |
for (unsigned int x = 0; x < copySize; ++x) | |
newData[x] = data[x]; | |
clear(); | |
data = newData; | |
size = arrSize; | |
} | |
private: | |
T *data; | |
unsigned int size; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment