Last active
June 10, 2021 21:12
-
-
Save stfuchs/082a568926d9c3a5c9aa88bd7fb7de74 to your computer and use it in GitHub Desktop.
Implement a simple vector class
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 <cstdint> | |
#include <cstring> | |
#include <iostream> | |
#include <vector> | |
using namespace std; | |
// use malloc and free instead of new and delete | |
// malloc take one argument that is a size in bytes of memory needed | |
// malloc returns a void* pointer to newly allocated memory | |
// when you are done with memory call free with pointer returned by malloc | |
// calling free allows memory to be used by other malloc requests | |
template <typename T> | |
class MyVector | |
{ | |
private: | |
// add member variables here | |
/** solution start **/ | |
size_t _size; | |
size_t _capacity; | |
T* _data; | |
/** solution end **/ | |
public: | |
MyVector() | |
/** solution start **/ | |
: _size(0), _capacity(0), _data(nullptr) | |
/** solution end **/ | |
{ | |
} | |
/** solution start **/ | |
~MyVector() | |
{ | |
free(_data); | |
} | |
MyVector(const MyVector& other) | |
{ | |
} | |
const MyVector& operator=(MyVector& other) | |
{ | |
} | |
/** solution end **/ | |
T& operator[] (size_t index) | |
{ | |
// fill in | |
/** solution start **/ | |
return _data[index]; | |
/** solution end **/ | |
} | |
void push_back(const T& value) | |
{ | |
// fill in | |
/** solution start **/ | |
if (_size == 0) | |
{ | |
_data = static_cast<T*>(malloc(sizeof(T))); | |
_capacity = 1; | |
} | |
if (_size == _capacity) | |
{ | |
_capacity *= 2; | |
T* data_new = static_cast<T*>(malloc(sizeof(T) * _capacity)); | |
for (size_t ii = 0; ii < _size; ++ii) | |
{ | |
data_new[ii] = _data[ii]; | |
} | |
//memcpy(data_new, _data, sizeof(T) * _size); | |
free(_data); | |
_data = data_new; | |
} | |
_data[_size] = value; | |
_size += 1; | |
/** solution end **/ | |
} | |
}; | |
int main() | |
{ | |
// when you switch to from std::vector to MyVector the output should be exactly the same | |
vector<float> vec; | |
//MyVector<float> vec; | |
size_t N = 100; | |
for (size_t ii = 0; ii < N; ++ii) | |
{ | |
vec.push_back(ii); | |
} | |
// put some random number at the start | |
for (size_t ii = 0; ii < N; ++ii) | |
{ | |
cout << vec[ii] << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment