I often found people use the array brackets [] and a normal vector function .at (). Why are there two separate methods? What are the benefits and disadvantages of both? I know that .at () is safer, but are there any situations where .at () cannot be used? And if .at () is always safer, why ever use array brackets [].
I searched around but couldn't find a similar question. If a questions like this already exists please forward me to it and I will delete this question.
std::vector::at()
guards you against accessing array elements out of bounds by throwing a std::out_of_range
exception unlike the []
operator which does not warn or throw exceptions when accessing beyond the vector bounds.
std::vector
is/was considered as a C++ replacement/construct for Variable Length Arrays(VLA) in c99. In order for C-style arrays to be easily replaceable by std::vector
it was necessary for vectors to provide a similar interface as that of an array, hence vector provides a []
operator for accessing its elements. At the same time, the C++ standards committee perhaps also felt the need for providing additional safety for std::vector
over C-style arrays and hence they also provided the std::vector::at()
method for this reason.
Naturally, the std::vector::at()
method checks for the size of the vector before dereferencing it and that will be a little overhead (perhaps negligible in most use cases) over accessing elements by []
, So std::vector
provides both options, to be safe or to be faster at expense of managing the safety yourself.