So I'm supposed to write some functions in class called ArrayList. I simply don't know where to start or how to manage with the dynamic array. The protected members of the class are:
protected:
int *m_list; ///< Pointer to dynamic array.
std::size_t m_capacity; ///< Physical size of dynamic array.
std::size_t m_size; ///< Number of array elements in use.
/// @brief Appends the given element @p value to the end of the container.
/// The new element is initialized as a copy of @p value.
/// If size() == capacity(), the container's size is increased to hold
/// an additional 16 elements. If the new size() is greater than
/// capacity(), then all references are invalidated.
/// @param value The value of the element to append.
void push_back(const int& value);
/// @brief Remove unused capacity. All iterators, including the past the
/// end iterator, and all references to the elements are invalidated.
void shrink_to_fit();
void ArrayList::shrink_to_fit()
{
}
void ArrayList::push_back(const int& value)
{
}
In shrink_to_fit
you need to resize the dynamic allocated memory and in push_back
you sometimes need to increase the allocated memory.
So one important piece of code you will need is a resize function, which will do the following:
shrink_to_fit
the new capacity is obviously size
. If you need to resize in push_back
you may want to increase the capacity not just by 1 to reduce the number of times you have to resize.new
. For example auto temp = new int[newCapacity];
m_list
to temp
using a loop or memcpy
.delete[] m_list;
capacity = newCapacity
and m_list = temp
.That's the hardest part of handling dynamic memory and I hope it will help you get started.
You will need dynamic memory allocation using new/delete
or malloc/free
to handle those methods. Start with allocating memory for 16 integers by appending them to the m_list
as a linked list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.