#include <iostream>
#include <string.h>
class MyVector {
private:
int *_pbegin;
int *_pend;
int *_pcapacity;
public:
MyVector() {
_pbegin = new int;
_pend = _pbegin;
_pcapacity = _pbegin + 1;
}
~MyVector() {
delete _pbegin;
}
void reallocate(size_t newCapacity) {
// Copy data into a temporary buffer
size_t prevSize = size();
int *prevData = new int[prevSize];
memcpy(prevData, _pbegin, prevSize * sizeof(int));
// Remove current data from memory and
// reallocate the amount of available memory
delete _pbegin;
_pbegin = new int[newCapacity];
_pend = _pbegin + prevSize;
_pcapacity = _pbegin + newCapacity;
//Copy previous data into the new memory
memcpy(_pbegin, prevData, prevSize * sizeof(int));
// Remove the temporary buffer from memory
delete prevData;
}
void push(int value) {
if (_pend == _pcapacity) {
reallocate(capacity() * 2);
}
*_pend = value;
_pend++;
}
int at(size_t pos) {
return _pbegin[pos];
}
size_t size() {
return _pend - _pbegin;
}
size_t capacity() {
return _pcapacity - _pbegin;
}
};
int main() {
MyVector vec;
std::cout << "Current size: " << vec.size() << std::endl;
std::cout << "Current capacity: " << vec.capacity() << std::endl << std::endl;
vec.push(42);
std::cout << "Inserted one element..." << std::endl;
std::cout << "Current size: " << vec.size() << std::endl;
std::cout << "Current capacity: " << vec.capacity() << std::endl << std::endl;
vec.push(1234);
std::cout << "Inserted one element..." << std::endl;
std::cout << "Current size: " << vec.size() << std::endl;
std::cout << "Current capacity: " << vec.capacity() << std::endl << std::endl;
vec.push(99);
std::cout << "Inserted one element..." << std::endl;
std::cout << "Current size: " << vec.size() << std::endl;
std::cout << "Current capacity: " << vec.capacity() << std::endl << std::endl;
vec.push(1);
vec.push(500);
std::cout << "Inserted two elements..." << std::endl;
std::cout << "Current size: " << vec.size() << std::endl;
std::cout << "Current capacity: " << vec.capacity() << std::endl << std::endl;
std::cout << "Listing each element..." << std::endl;
for (size_t i = 0; i < vec.size(); ++i) {
printf("vec[%u] => %d\n", i, vec.at(i));
}
std::cout << std::endl;
}