Browse Source

resize for heap arrays

Kajetan Johannes Hammerle 3 years ago
parent
commit
11d3bae3ac
2 changed files with 29 additions and 0 deletions
  1. 15 0
      tests/HeapArrayTests.cpp
  2. 14 0
      utils/HeapArray.h

+ 15 - 0
tests/HeapArrayTests.cpp

@@ -19,9 +19,24 @@ static void testToString2(Test& test) {
     test.checkEqual(String("[1]"), String(a), "to string 2");
 }
 
+static void testGrow(Test& test) {
+    HeapArray<int> a(3);
+    a[0] = 1;
+    a[1] = 2;
+    a[2] = 3;
+    a.grow(2, 20);
+    test.checkEqual(5, a.getLength(), "resize length");
+    test.checkEqual(1, a[0], "resize copy 1");
+    test.checkEqual(2, a[1], "resize copy 2");
+    test.checkEqual(3, a[2], "resize copy 3");
+    test.checkEqual(20, a[3], "resize copy 4");
+    test.checkEqual(20, a[4], "resize copy 5");
+}
+
 void HeapArrayTests::test() {
     Test test("HeapArray");
     testToString1(test);
     testToString2(test);
+    testGrow(test);
     test.finalize();
 }

+ 14 - 0
utils/HeapArray.h

@@ -73,6 +73,20 @@ public:
         return length;
     }
 
+    void grow(int growth, const T& t) {
+        int newLength = length + growth;
+        T* newData = new T[newLength];
+        for(int i = 0; i < length; i++) {
+            newData[i] = std::move(data[i]);
+        }
+        for(int i = length; i < newLength; i++) {
+            newData[i] = t;
+        }
+        delete[] data;
+        data = newData;
+        length = newLength;
+    }
+
     template<int L>
     void toString(StringBuffer<L>& s) const {
         s.append("[");