Using the [] Operator to Access and Modify vector Elements

Lines 68 and 70 use square brackets ([]) to obtain a vector element and use it as an rvalue and as an lvalue, respectively. Recall from Section 5.9 that an rvalue cannot be modified, but an lvalue can. As is the case with arrays, C++ is not required to perform bounds checking when vector elements are accessed with square brackets.1 Therefore, you must ensure that operations using [] do not accidentally attempt to manipulate elements outside the bounds of the vector. Standard class template vector does, however, provide bounds checking in its member function at (as does class template array), which we use at line 80 and discuss shortly.

1. Some compilers have options for bounds checking ...

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.