summaryrefslogtreecommitdiff
path: root/AK/Vector.h
diff options
context:
space:
mode:
authorAndreas Kling <kling@serenityos.org>2022-11-26 20:32:33 +0100
committerLinus Groh <mail@linusgroh.de>2022-12-08 23:36:17 +0000
commitd77ce7bae9eebf2935a64b96308b8c239ad39213 (patch)
treecbe9ac232f84c37c8721b600141ed4abc07949ff /AK/Vector.h
parent35ed82d5e620546ffd49186a0ee62c72ea8fffa5 (diff)
downloadserenity-d77ce7bae9eebf2935a64b96308b8c239ad39213.zip
AK: Add Vector::shrink_to_fit()
If there's more capacity than size, the vector is reallocated to have capacity == size.
Diffstat (limited to 'AK/Vector.h')
-rw-r--r--AK/Vector.h12
1 files changed, 12 insertions, 0 deletions
diff --git a/AK/Vector.h b/AK/Vector.h
index 4031f6ec5b..e0fce22193 100644
--- a/AK/Vector.h
+++ b/AK/Vector.h
@@ -729,6 +729,18 @@ public:
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 Iterator = SimpleIterator<Vector, VisibleType>;
using ReverseIterator = SimpleReverseIterator<Vector, VisibleType>;