简体   繁体   English

我不知道如何设计 function 以使用动态数组

[英]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.所以我应该在 class 中编写一些函数,称为 ArrayList。 I simply don't know where to start or how to manage with the dynamic array.我根本不知道从哪里开始或如何使用动态数组进行管理。 The protected members of the class are: class 的受保护成员是:

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.shrink_to_fit ,您需要调整动态分配的memory 的大小,而在push_back中,您有时需要增加分配的memory。

So one important piece of code you will need is a resize function, which will do the following:因此,您需要的一段重要代码是调整 function 的大小,它将执行以下操作:

  1. determine the new capacity needed.确定所需的新容量。 In shrink_to_fit the new capacity is obviously size .shrink_to_fit中,新容量显然是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.如果您需要在push_back中调整大小,您可能希望增加容量,而不仅仅是增加 1 以减少您必须调整大小的次数。
  2. allocate memory of the required capacity using new .使用new分配所需容量的 memory 。 For example auto temp = new int[newCapacity];例如auto temp = new int[newCapacity];
  3. Copy all existing items from m_list to temp using a loop or memcpy .使用循环或memcpy将所有现有项目从m_list复制到temp
  4. delte the old memory using delete[] m_list;使用delete[] m_list;
  5. adjust local variables: capacity = newCapacity and m_list = temp .调整局部变量: capacity = newCapacitym_list = temp

That's the hardest part of handling dynamic memory and I hope it will help you get started.这是处理动态 memory 最难的部分,我希望它能帮助您入门。

You will need dynamic memory allocation using new/delete or malloc/free to handle those methods.您将需要使用new/deletemalloc/free动态分配 memory 来处理这些方法。 Start with allocating memory for 16 integers by appending them to the m_list as a linked list.首先为 16 个整数分配 memory,方法是将它们作为链表附加到m_list中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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