first commit
This commit is contained in:
101
ArrayStack/Cpp/arraystack.cpp
Normal file
101
ArrayStack/Cpp/arraystack.cpp
Normal file
@@ -0,0 +1,101 @@
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
|
||||
template <typename T, size_t growSize = 10, size_t initialSize = 0> class ArrayStack
|
||||
{
|
||||
public:
|
||||
ArrayStack()
|
||||
:
|
||||
m_array(nullptr)
|
||||
, m_arrayLen(0)
|
||||
, m_currentHead(0)
|
||||
, m_growSize(growSize)
|
||||
{
|
||||
if (initialSize > 0)
|
||||
{
|
||||
grow(initialSize);
|
||||
}
|
||||
}
|
||||
|
||||
~ArrayStack()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void push(T obj)
|
||||
{
|
||||
if (m_currentHead+1 >= m_arrayLen)
|
||||
{
|
||||
grow();
|
||||
}
|
||||
|
||||
m_array[m_currentHead] = obj;
|
||||
m_currentHead++;
|
||||
}
|
||||
|
||||
void pop(T *obj)
|
||||
{
|
||||
if (m_currentHead > 0)
|
||||
{
|
||||
auto temp = m_array[m_currentHead-1];
|
||||
*obj = temp;
|
||||
m_currentHead--;
|
||||
}
|
||||
else
|
||||
{
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
void grow(size_t size = growSize)
|
||||
{
|
||||
// Allocate for the new size
|
||||
auto newArrayLen = size + m_arrayLen;
|
||||
auto newArray = (T*)malloc(sizeof(T) * newArrayLen);
|
||||
|
||||
// Copy over the old array
|
||||
if (newArray)
|
||||
{
|
||||
memcpy(newArray, m_array, m_arrayLen * sizeof(T));
|
||||
}
|
||||
|
||||
// delete the old one
|
||||
if (m_array) free(m_array);
|
||||
|
||||
// Set the new array
|
||||
m_array = newArray;
|
||||
m_arrayLen = newArrayLen;
|
||||
}
|
||||
|
||||
|
||||
T *m_array;
|
||||
size_t m_arrayLen;
|
||||
size_t m_currentHead;
|
||||
const size_t m_growSize;
|
||||
};
|
||||
|
||||
#ifndef EXTERN_MAIN
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
ArrayStack<int> stack;
|
||||
const size_t stackSize = 50;
|
||||
|
||||
for (size_t i = 0; i < stackSize; i++)
|
||||
{
|
||||
stack.push(i);
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < stackSize; i++)
|
||||
{
|
||||
int dest;
|
||||
stack.pop(&dest);
|
||||
printf("Got: %d\n", dest);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
Reference in New Issue
Block a user