@@ -19,6 +19,69 @@ class vector {
1919 delete[] m_data; // free memory in destructor
2020 }
2121
22+ /* *
23+ * @brief Set the capacity of the vector.
24+ * @param new_capacity The new capacity for the vector.
25+ * @return void.
26+ */
27+ void reserve (const std::size_t new_capacity) {
28+ // reserve only affects capacity not size
29+ // therefore a reserving an amount smaller than size will be ignored
30+
31+ if (new_capacity > m_capacity) {
32+ reallocate (new_capacity);
33+ }
34+ }
35+
36+ /* *
37+ * @brief Set the size of the vector.
38+ * @param new_size The new size for the vector.
39+ * @return void.
40+ */
41+ void resize (const std::size_t new_size) {
42+ // resize affects size and capacity
43+ // therefore a resizing an amount smaller than size will shrink the vector
44+
45+ // reserve more space if needed
46+ if (new_size > m_capacity) reallocate (new_size);
47+
48+ // shrink if needed
49+ for (std::size_t i = new_size; i < m_size; ++i) {
50+ m_data[i].~T (); // call destructor explicitly
51+ }
52+
53+ // if growing, initialize new elements with default constructor
54+ for (std::size_t i = m_size; i < new_size; ++i) {
55+ new (&m_data[i]) T ();
56+ }
57+
58+ m_size = new_size;
59+ }
60+
61+ /* *
62+ * @brief Set the size of the vector.
63+ * @param new_size The new size for the vector.
64+ * @param val The value to initialize new elements with.
65+ * @return void.
66+ */
67+ void resize (const std::size_t new_size, const T& val) {
68+
69+ // reserve more space if needed
70+ if (new_size > m_capacity) reallocate (new_size);
71+
72+ // shrink if needed
73+ for (std::size_t i = new_size; i < m_size; ++i) {
74+ m_data[i].~T (); // call destructor explicitly
75+ }
76+
77+ // if growing, initialize new elements with val
78+ for (std::size_t i = m_size; i < new_size; ++i) {
79+ new (&m_data[i]) T (val);
80+ }
81+
82+ m_size = new_size;
83+ }
84+
2285 /* *
2386 * @brief Add an element to the end of the vector.
2487 * @param value The value to add to the end of the vector.
@@ -121,6 +184,8 @@ class vector {
121184 */
122185 void reallocate (std::size_t new_capacity) {
123186
187+ // reserc
188+
124189 // TODO: handle reallocation for shrinking
125190 if (new_capacity <= m_size) {
126191 m_size = new_capacity;
0 commit comments