Accessing elements of a vector in C++?

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 replacable by std::vector it was needed that vectors 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 std::vector::at() method which provides it.

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 you both the options to be safe or to be faster at expense of managing the safety yourself.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)