@@ -12,7 +12,7 @@ class vector {
1212 // TODO: provide allocator felxibility
1313 vector () {
1414 // allocate memory in cosntructor
15- reallocate (2 ); // initial capacity of 2
15+ reallocate (4 ); // initial capacity of 2
1616 }
1717
1818 ~vector () {
@@ -34,6 +34,59 @@ class vector {
3434 m_size++;
3535 }
3636
37+ /* *
38+ * @brief Add an element to the end of the vector.
39+ * @param value The (R-value ref) value to add to the end of the vector.
40+ * @return void.
41+ */
42+ void push_back (T&& value) {
43+ if (m_size >= m_capacity) {
44+ reallocate (m_capacity * 2 ); // double the capacity - TODO: use an allcoater to be dynamic
45+ }
46+
47+ // add element to the end of the vector
48+ m_data[m_size] = std2::move (value);
49+ m_size++;
50+ }
51+
52+ /* *
53+ * @brief Add an element to the end of the vector.
54+ * @param args Arguments to forward to the constructor of T.
55+ * @return T reference.
56+ */
57+ template <typename ... Args> // variadic template
58+ T& emplace_back (Args&&... args) {
59+ if (m_size >= m_capacity) {
60+ reallocate (m_capacity * 2 ); // double the capacity - TODO: use an allcoater to be dynamic
61+ }
62+
63+ // add element to the end of the vector
64+ m_data[m_size] = T (std2::forward<Args>(args)...);
65+ return m_data[m_size++];
66+ }
67+
68+ /* *
69+ * @brief Remove the last element from the vector.
70+ * @return void.
71+ */
72+ void pop_back () {
73+ if (m_size > 0 ) {
74+ m_size--;
75+ m_data[m_size].~T (); // call destructor explicitly
76+ }
77+ }
78+
79+ /* *
80+ * @brief Clear the vector - remove all elements.
81+ * @return void.
82+ */
83+ void clear () {
84+ for (size_t i = 0 ; i < m_size; ++i) {
85+ m_data[i].~T (); // call destructor explicitly
86+ }
87+ m_size = 0 ;
88+ }
89+
3790 /* *
3891 * @brief Get the number of elements in the vector.
3992 * @return the number of elements in the vector.
@@ -54,7 +107,7 @@ class vector {
54107 /* *
55108 * @brief Index operator - access element at the given index.
56109 * @param index The index of the element to access.
57- * @return the value at the index.
110+ * @return the referecne to the value at the index.
58111 */
59112 T& operator [](std::size_t index) {
60113 return m_data[index];
@@ -77,8 +130,8 @@ class vector {
77130 T* new_block = new T[new_capacity];
78131
79132 for (std::size_t i = 0 ; i < m_size; ++i) {
80- // new_block[i] = std2::move(m_data[i]);
81- new_block[i] = m_data[i];
133+ new_block[i] = std2::move (m_data[i]);
134+ // new_block[i] = m_data[i];
82135 }
83136
84137 delete[] m_data; // free old memory block
0 commit comments