瀏覽代碼

AK: Add Vector::shrink_to_fit()

If there's more capacity than size, the vector is reallocated to have
capacity == size.
Andreas Kling 2 年之前
父節點
當前提交
d77ce7bae9
共有 1 個文件被更改,包括 12 次插入0 次删除
  1. 12 0
      AK/Vector.h

+ 12 - 0
AK/Vector.h

@@ -729,6 +729,18 @@ public:
         MUST(try_resize_and_keep_capacity(new_size));
         MUST(try_resize_and_keep_capacity(new_size));
     }
     }
 
 
+    void shrink_to_fit()
+    {
+        if (size() == capacity())
+            return;
+        Vector new_vector;
+        new_vector.ensure_capacity(size());
+        for (auto& element : *this) {
+            new_vector.unchecked_append(move(element));
+        }
+        *this = move(new_vector);
+    }
+
     using ConstIterator = SimpleIterator<Vector const, VisibleType const>;
     using ConstIterator = SimpleIterator<Vector const, VisibleType const>;
     using Iterator = SimpleIterator<Vector, VisibleType>;
     using Iterator = SimpleIterator<Vector, VisibleType>;
     using ReverseIterator = SimpleReverseIterator<Vector, VisibleType>;
     using ReverseIterator = SimpleReverseIterator<Vector, VisibleType>;