Browse Source

improved resize

Kajetan Johannes Hammerle 3 years ago
parent
commit
5b96690b59
3 changed files with 20 additions and 1 deletions
  1. 4 0
      Main.cpp
  2. 16 1
      Vector.h
  3. BIN
      Vector.zip

+ 4 - 0
Main.cpp

@@ -1,5 +1,6 @@
 #include "Vector.h"
 #include <iostream>
+#include <memory>
 #include <vector>
 
 // All implementations in this class use ints insteads of size_t because size_t
@@ -170,4 +171,7 @@ int main() {
     test<std::vector<A>>();
 
     Vector<int> test(3);
+
+    Vector<std::unique_ptr<A>> test2;
+    test2.resize(5);
 }

+ 16 - 1
Vector.h

@@ -3,6 +3,7 @@
 
 #include <cassert>
 #include <new>
+#include <utility>
 
 template<typename T>
 class Vector {
@@ -88,7 +89,21 @@ public:
     }
 
     void resize(int size) {
-        resize(size, T());
+        // calling resize(size, T()); would break structures which can be
+        // default constructed but not copied e.g. unique pointers elements will
+        // be equal to size after this call but not the capacity
+        if(size > elements) {
+            // fill until the given size is reached
+            for(int i = elements; i < size; i++) {
+                push_back(T());
+            }
+        } else if(size < elements) {
+            // remove objects until the size matches
+            for(int i = size; i < elements; i++) {
+                data[i].~T();
+            }
+            elements = size;
+        }
     }
 
     void push_back(const T& t) {

BIN
Vector.zip