=====at=====
Syntax:
#include
TYPE& at( size_type loc );
const TYPE& at( size_type loc ) const;
The at() function returns a reference to the element in the vector at
index loc. The at() function is safer than the [[vector_operators|[]
operator]], because it won't let you reference items outside the bounds
of the vector.
For example, consider the following code:
vector v( 5, 1 );
for( int i = 0; i < 10; i++ ) {
cout << "Element " << i << " is " << v[i] << endl;
}
This code overruns the end of the vector, producing potentially dangerous
results. The following code would be much safer:
vector v( 5, 1 );
for( int i = 0; i < 10; i++ ) {
cout << "Element " << i << " is " << v.at(i) << endl;
}
Instead of attempting to read garbage values from memory, the at() function
will realize that it is about to overrun the vector and will throw an
exception (out_of_range).
Related Topics: [[vector_operators|[] operator]]