我不知道如何设计函数以使用动态数组
I don't know how to design the function to work with the dynamic array
所以我应该在名为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 函数,它将执行以下操作:
- 确定所需的新容量。
shrink_to_fit
新产能显然size
.如果需要调整大小push_back
则可能需要增加容量,而不仅仅是增加 1,以减少必须调整大小的次数。 - 使用
new
分配所需容量的内存。例如auto temp = new int[newCapacity];
- 使用循环或
memcpy
将所有现有项目从m_list
复制到temp
。 - 使用
delete[] m_list;
删除旧内存 - 调整局部变量:
capacity = newCapacity
和m_list = temp
。
这是处理动态内存最困难的部分,我希望它能帮助您入门。
您需要使用new/delete
或malloc/free
进行动态内存分配来处理这些方法。首先为 16 个整数分配内存,方法是将它们作为链表附加到m_list
。
相关文章:
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 输出没有重复元素的动态数组(收缩数组)C++
- 正在插入动态数组
- 如何在动态数组上使用搜索函数
- C++ 动态数组每次添加时将大小增加 1 - 错误
- 静态数组的自由动态数组
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 使用 thread 类在 C++ 中构造线程的动态数组时出错
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用
- 为什么 c++ 动态数组的大小没有改变?
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 指针的 C++ 动态数组 - 何时需要使用它?
- 删除动态数组时未定义标识符
- 哈希映射使用 nullptr c++ 初始化节点的动态数组
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 动态数组的 C++ 重载加运算符
- 基于数组的列表 - 动态数组创建时出错