at

Syntax:

    #include <vector>
    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 [] operator, because it won't let you reference items outside the bounds of the vector.

For example, consider the following code:

   vector<int> 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<int> 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: [] operator