Browse Source

list extension

Kajetan Johannes Hammerle 2 years ago
parent
commit
e77275d7db
2 changed files with 30 additions and 0 deletions
  1. 17 0
      data/List.h
  2. 13 0
      tests/ListTests.cpp

+ 17 - 0
data/List.h

@@ -66,6 +66,19 @@ public:
         swap(copy);
     }
 
+    void shrink() {
+        if(length == capacity) {
+            return;
+        }
+        List copy;
+        copy.capacity = length;
+        copy.data = allocate(length);
+        for(int i = 0; i < length; i++) {
+            copy.add(std::move(data[i]));
+        }
+        swap(copy);
+    }
+
     void resize(int n, const T& t) {
         if(length < n) {
             reserve(n);
@@ -125,6 +138,10 @@ public:
         return length;
     }
 
+    int getCapacity() const {
+        return capacity;
+    }
+
     void clear() {
         for(int i = 0; i < length; i++) {
             data[i].~T();

+ 13 - 0
tests/ListTests.cpp

@@ -37,6 +37,18 @@ static void testClear(Test& test) {
     test.checkEqual(0, list.getLength(), "length is 0 after clear");
 }
 
+static void testShrink(Test& test) {
+    IntList list;
+    list.add(5).add(4).add(3);
+    test.checkTrue(list.getCapacity() >= 3, "capacity is >= 3 after adding");
+    list.shrink();
+    test.checkTrue(list.getLength() == 3, "length is 3 after shrink");
+    test.checkTrue(list.getCapacity() == 3, "capacity is 3 after shrink");
+    test.checkEqual(5, list[0], "data ok after shrink 1");
+    test.checkEqual(4, list[1], "data ok after shrink 2");
+    test.checkEqual(3, list[2], "data ok after shrink 3");
+}
+
 static void testBigAdd(Test& test) {
     IntList list;
     for(int i = 0; i < 1000000; i++) {
@@ -148,6 +160,7 @@ void ListTests::test() {
     testMultipleAdd(test);
     testAddReplace(test);
     testClear(test);
+    testShrink(test);
     testBigAdd(test);
     testCopy(test);
     testCopyAssignment(test);