简体   繁体   中英

I don't know how to design the function to work with the dynamic array

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:

  1. determine the new capacity needed. In 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.
  2. allocate memory of the required capacity using new . For example auto temp = new int[newCapacity];
  3. Copy all existing items from m_list to temp using a loop or memcpy .
  4. delte the old memory using delete[] m_list;
  5. adjust local variables: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM