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

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

本文关键字:动态 数组 函数 我不知道      更新时间:2023-10-16

所以我应该在名为ArrayList的类中编写一些函数。我根本不知道从哪里开始或如何使用动态数组进行管理。类的受保护成员包括:

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)
{
}

shrink_to_fit中,您需要调整动态分配内存的大小,push_back有时需要增加分配的内存。

因此,您需要的一段重要代码是 resize 函数,它将执行以下操作:

  1. 确定所需的新容量。shrink_to_fit新产能显然size.如果需要调整大小push_back则可能需要增加容量,而不仅仅是增加 1,以减少必须调整大小的次数。
  2. 使用new分配所需容量的内存。例如auto temp = new int[newCapacity];
  3. 使用循环或memcpy将所有现有项目从m_list复制到temp
  4. 使用delete[] m_list;删除旧内存
  5. 调整局部变量:capacity = newCapacitym_list = temp

这是处理动态内存最困难的部分,我希望它能帮助您入门。

您需要使用new/deletemalloc/free进行动态内存分配来处理这些方法。首先为 16 个整数分配内存,方法是将它们作为链表附加到m_list