027: emplace()

emplace() を定義します。C++11 から追加された関数です。

emplace() は insert() とほとんど同じ動作になります。

template <typename T>
class myvector
{
...

    /**
     * @brief      Inserts a new element into the container directly before pos.
     *             The arguments args... are forwarded to the constructor as
     *             std::forward<Args>(args)....
     *             If the new size() is greater than capacity(), all iterators and
     *             references are invalidated. Otherwise, only the iterators and
     *             references before the insertion point remain valid. The past-the-end
     *             iterator is also invalidated.
     * @param[in]  pos: Iterator before which the new element will be constructed. pos
     *                  may be the end() iterator.
     * @param[in]  args: Arguments to forward to the constructor of the element.
     * @tparam     Args: Parameter pack for constructor's arguments.
     * @return     Iterator pointing to the inserted value.
     */
    template <class... Args>
    iterator emplace(const_iterator pos, Args&&... args)
    {
        // calculate distance
        size_type distance = mydistance(static_cast<const_iterator>(&heap_[0]), pos, std::random_access_iterator_tag());

        // re-allocate if needed
        if (need_twice_capacity()) {
            reallocation(twice_length(), realloc_switcher());
        }

        // slide elements after pos
        incremental_slide(distance, 1, slide_switcher());
        // set inserted element
        new(&heap_[distance]) value_type(std::forward<Args&&>(args)...);
        size_++;

        return static_cast<iterator>(&heap_[distance]);
    }

    ...
};
①挿入後のサイズ計算、②領域確保、③既存要素の移動、④新要素の代入、という処理の流れになるのは、insert() と同じです。
新要素の作成には、C++11 の新文法であるコンストラクタ引数列を使用します。


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

0 件のコメント:

コメントを投稿