template <typename T> class myvector { ... /** * @brief Returns an iterator to the first element of the container. * If the container is empty, the returned iterator will be equal * to end(). * @return Iterator to the first element. */ iterator begin(void) noexcept { return heap_; } /** * @brief Returns a const iterator to the first element of the container. * If the container is empty, the returned iterator will be equal * to end(). * @return Const iterator to the first element. */ const_iterator begin(void) const noexcept { return heap_; } /** * @brief Returns a const iterator to the first element of the container. * If the container is empty, the returned iterator will be equal * to cend(). * @return Const iterator to the first element. */ const_iterator cbegin(void) const noexcept { return heap_; } /** * @brief Returns an iterator to the element following the last element * of the container. * This element acts as a placeholder; attempting to access it * results in undefined behavior. * @return Iterator to the element following the last element. */ iterator end(void) noexcept { return heap_ + size_; } /** * @brief Returns a const iterator to the element following the last element * of the container. * This element acts as a placeholder; attempting to access it * results in undefined behavior. * @return Const iterator to the element following the last element. */ const_iterator end(void) const noexcept { return heap_ + size_; } /** * @brief Returns a const iterator to the element following the last element * of the container. * This element acts as a placeholder; attempting to access it * results in undefined behavior. * @return Const iterator to the element following the last element. */ const_iterator cend(void) const noexcept { return heap_ + size_; } ... private: pointer heap_ = nullptr; size_type size_ = 0; size_type capacity_ = 0; };begin()系の関数が3つ、end()系の関数が3つ、それぞれ定義されています。const の有無を除けば、行っていることは同じです。
begin() は メンバ変数 heap_ の生の値を返します。これは return &(heap_[0]); と同じことになります。
end() は heap_ + size_ の値を返します。これは return &(heap_[size_]); と同じことになります。一見すると heap_[size_] は確保領域の範囲外のように見えてしまいますが、&(heap_[size_]) が有効なポインタ値であることは保証されています( *(heap_[size_]) は有効な値ではない)。
前々回の size()、前回の capacity()、今回の begin() と end() の定義をもって、プリミティブなアクセス関数は完了となります。次回以降は、領域確保を伴う処理の実装に入っていきます。
全ソースコード:
https://github.com/suomesta/myvector/tree/master/006
0 件のコメント:
コメントを投稿