簡體   English   中英

我不知道如何設計 function 以使用動態數組

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

所以我應該在 class 中編寫一些函數,稱為 ArrayList。 我根本不知道從哪里開始或如何使用動態數組進行管理。 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)
{

}

shrink_to_fit ,您需要調整動態分配的memory 的大小,而在push_back中,您有時需要增加分配的memory。

因此,您需要的一段重要代碼是調整 function 的大小,它將執行以下操作:

  1. 確定所需的新容量。 shrink_to_fit中,新容量顯然是size 如果您需要在push_back中調整大小,您可能希望增加容量,而不僅僅是增加 1 以減少您必須調整大小的次數。
  2. 使用new分配所需容量的 memory 。 例如auto temp = new int[newCapacity];
  3. 使用循環或memcpy將所有現有項目從m_list復制到temp
  4. 使用delete[] m_list;
  5. 調整局部變量: capacity = newCapacitym_list = temp

這是處理動態 memory 最難的部分,我希望它能幫助您入門。

您將需要使用new/deletemalloc/free動態分配 memory 來處理這些方法。 首先為 16 個整數分配 memory,方法是將它們作為鏈表附加到m_list中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM