Files
datastructures/sequential/vector.hpp

89 lines
1.4 KiB
C++

#pragma once
#include <cstdlib>
#include <stdexcept>
template<class T>
class Vector
{
private:
T * data;
std::size_t byteSize;
std::size_t reserveSize;
std::size_t size;
void Allocate(std::size_t const allocationSize)
{
if(allocationSize == 0ul)
{
std::free(data);
data = nullptr;
byteSize = 0ul;
reserveSize = 0ul;
return;
}
std::size_t newByteSize = allocationSize * sizeof(T);
newByteSize += newByteSize % 32ul; // Allocate in blocks of 32 bytes
if(newByteSize <= byteSize)
{
reserveSize = allocationSize;
return;
}
void * result = std::realloc(data, newByteSize);
if(result == nullptr)
{
throw std::runtime_error("Cannot allocate the requested size of memory.");
}
byteSize = newByteSize;
reserveSize = allocationSize;
data = reinterpret_cast<T *>(result);
}
public:
void Resize(std::size_t const newSize)
{
if (newSize > reserveSize)
{
Allocate(newSize);
size = newSize;
return;
}
size = newSize;
}
void Reserve(std::size_t const newReserveSize)
{
if(newReserveSize < size)
{
Allocate(size);
return;
}
Allocate(newReserveSize);
}
T & operator[](std::size_t const index)
{
if(index >= size)
{
throw std::out_of_range("Index is greater or equal to size.");
}
return data[index];
}
std::size_t GetSize() const
{
return size;
}
Vector()
: data(nullptr),
byteSize(0ul),
reserveSize(0ul),
size(0ul)
{}
};