at() は operator[]() とほぼ同じ形ですが、引数が範囲外の場合に std::out_of_range を投げる点が異なります。
template <typename T>
class myvector
{
...
/**
* @brief Returns a reference to the element at specified location pos,
* with bounds checking. If pos is not within the range of the container,
* an exception of type std::out_of_range is thrown.
* @param[in] pos: Position of the element to return.
* @return Reference to the requested element.
* @throw std::out_of_range: If pos is not within the range of the container.
*/
reference at(size_type pos)
{
if (pos >= size_) {
throw std::out_of_range("myvector::at()");
}
return heap_[pos];
}
/**
* @brief Returns a reference to the element at specified location pos,
* with bounds checking. If pos is not within the range of the container,
* an exception of type std::out_of_range is thrown.
* @param[in] pos: Position of the element to return.
* @return Const reference to the requested element.
* @throw std::out_of_range: If pos is not within the range of the container.
*/
const_reference at(size_type pos) const
{
if (pos >= size_) {
throw std::out_of_range("myvector::at() const");
}
return heap_[pos];
}
...
};
at() は2種類ありますが、違いは const関数であるか、非const関数であるか、のみです。
全ソースコード: https://github.com/suomesta/myvector/tree/master/019
0 件のコメント:
コメントを投稿