015: resize()

resize() を定義します。

サイズが小さくなる場合と、大きくなる場合とで、処理の内容が異なります。

template <typename T>
class myvector
{
...

    /**
     * @brief      Resizes the container to contain count elements.
     *             If the current size is greater than count, the container is reduced
     *             to its first count elements.
     * @param[in]  count: New size of the container.
     * @throw      std::length_error: If count is greater than max_size().
     * @throw      std::bad_alloc: If malloc() (or realloc()) fails to allocate storage.
     */
    void resize(size_type count)
    {
        if (count < size_) { // reduce size
            // call destructor to elements to be removed
            for (size_type i = count; i < size_; i++) {
                heap_[i].~value_type();
            }
            size_ = count;
        }
        else if (count > size_) { // enlarge size
            if (count > capacity_) { // expand capacity if needed
                reallocation(length_check(count), realloc_switcher());
            }
            // call placement-new to the expanded elements
            for (size_type i = size_; i < count; i++) {
                new(&heap_[i]) value_type();
            }
            size_ = count;
        }
    }

    /**
     * @brief      Resizes the container to contain count elements.
     *             If the current size is greater than count, the container is reduced
     *             to its first count elements.
     * @param[in]  count: New size of the container.
     * @param[in]  value: The value to initialize the new elements with.
     * @throw      std::length_error: If count is greater than max_size().
     * @throw      std::bad_alloc: If malloc() (or realloc()) fails to allocate storage.
     */
    void resize(size_type count, const value_type& value)
    {
        if (count < size_) { // reduce size
            // call destructor to elements to be removed
            for (size_type i = count; i < size_; i++) {
                heap_[i].~value_type();
            }
            size_ = count;
        }
        else if (count > size_) { // enlarge size
            if (count > capacity_) { // expand capacity if needed
                reallocation(length_check(count), realloc_switcher());
            }
            // call placement-new to the expanded elements
            for (size_type i = size_; i < count; i++) {
                new(&heap_[i]) value_type(value);
            }
            size_ = count;
        }
    }
...

};
引数count が現在の size_ よりも小さい場合、size_以降の要素に対してデストラクタを呼んだ後、size_ を小さくします。capacity_ は変更されません。

引数count が現在の size_ よりも大きい場合、まず count が capacity_ よりも大であれば、reserve() 相当の処理を行い、capacity_ を大きくします。続いて、size_以降の領域に対してコンストラクタを呼んだ後、size_ を大きくします。

引数の数が1つの resize() と2つの resize() の違いは、コンストラクタを呼ぶ時に、デフォルトコンストラクタを呼ぶか、コピーコンストラクタを呼ぶか、という点のみです。


全ソースコード: https://github.com/suomesta/myvector/tree/master/015

0 件のコメント:

コメントを投稿