C++ 我不知道';我不知道如何设计与动态数组一起使用的函数
所以我应该在名为ArrayList的类中编写一些函数。我根本不知道从哪里开始,也不知道如何使用动态阵列进行管理。该类受保护的成员包括:C++ 我不知道';我不知道如何设计与动态数组一起使用的函数,c++,dynamic-arrays,C++,Dynamic Arrays,所以我应该在名为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 u
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)
{
}
受保护:
int*m_列表;//<指向动态数组的指针。
标准:容量动态数组的物理大小。
标准::大小正在使用的数组元素数。
///@brief将给定元素@p值附加到容器的末尾。
///新元素初始化为@p value的副本。
///如果size()==capacity(),则容器的大小将增加到可容纳
///增加16个元素。如果新大小()大于
///capacity(),则所有引用均无效。
///@param value要追加的元素的值。
无效回推(常数int和值);
///@brief删除未使用的容量。所有迭代器,包括过去的
///结束迭代器,所有对元素的引用都将无效。
无效收缩至配合();
void ArrayList::收缩到
{
}
void ArrayList::push_back(常量int和值)
{
}
您需要使用new/delete
或malloc/free
动态分配内存来处理这些方法。首先为16个整数分配内存,方法是将它们作为链表添加到m\u列表中。在shorn\u to\u fit
中,需要调整动态分配内存的大小,在推回
中,有时需要增加分配的内存
因此,您需要的一段重要代码是resize函数,它将执行以下操作:
确定所需的新容量。在shorn\u to_fit
中,新容量显然是size
。如果您需要在push_back
中调整大小,您可能希望增加容量,而不仅仅是增加1,以减少调整大小的次数
使用new
分配所需容量的内存。例如autotemp=newint[newCapacity]代码>
使用循环或memcpy
将所有现有项目从m_列表复制到temp
使用delete[]m_list删除旧内存代码>
调整局部变量:capacity=newCapacity
和m\u list=temp
这是处理动态内存最困难的部分,我希望它能帮助您开始。看起来您的任务是创建一个动态内存。看看这一点,可以得到一些想法。命名在编程中很重要。因此,您应该决定是要实现动态数组别名向量还是列表。ArrayList听起来像一个数组列表…这显然不是一个链表,但更像是一个向量。评论不错,但我相信这不是一个答案!谢谢你的评论!