Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstddef>
- #include <iostream>
- template<typename T>
- class Vector {
- private:
- class RawMemory {
- public:
- T * data[];
- RawMemory (size_t sz = 0) {
- data = new T[sz];
- }
- RawMemory (const RawMemory& other) {
- size_t i = 0;
- data = new T[other.size];
- try {
- for (; i < other.size; i++) {
- *(data[i]) = *(other.data[i]);
- }
- } catch (...) {
- for (int j= 0; j < i; j++) {
- delete data[i];
- delete [] data;
- }
- }
- }
- void Swap(RawMemory other) {
- std::swap(data, other.data);
- }
- ~RawMemory() {
- for (auto x : data) {
- delete x;
- }
- delete [] data;
- }
- };
- RawMemory raw;
- size_t siz = 0;
- size_t capacity = 0;
- public:
- Vector(size_t sz = 0) : siz(sz), capacity(sz), raw(sz){}
- Vector(const Vector& other) : siz(other.siz), capacity(other.capacity), raw(other.raw){}
- Vector& operator =(Vector&& other) {
- std::swap(siz, other.siz);
- std::swap(capacity, other.capacity);
- Swap(raw, other.raw);
- }
- Vector& operator =(const Vector& other) {
- auto tmp(other);
- (*this) = move(tmp);
- return *this;
- }
- size_t size() {
- return siz;
- }
- void pop_back() {
- delete raw.data[siz - 1];
- siz--;
- }
- void push_back(const T& elem) {
- if (siz == capacity) {
- RawMemory tmp(raw.data);
- for (auto i = 0; i < siz; i++) {
- delete raw.data[i];
- }
- delete [] raw.data;
- size_t oldsiz = siz;
- if (siz > 0) {
- siz *= 2;
- capacity *= 2;
- } else {
- siz = 1;
- capacity = 1;
- }
- raw.data = new T[siz];
- for (size_t i = 0; i < oldsiz; i++) {
- raw.data[i] = tmp.data[i];
- }
- }
- raw.data[siz] = elem;
- siz++;
- }
- T& operator[](size_t ind) {
- return *(raw.data[ind]);
- }
- const T& operator[](size_t ind) const{
- return *(raw.data[ind]);
- }
- ~Vector(){}
- };
- int main()
- {
- Vector<int> a(3);
- a[0] = 2;
- a[1] = 3;
- a[2] = 1;
- std::cout << a[0] << " " << a[1] << " " << a[2] << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement