at [C++ Reference]
Keywords: stl,vector,at
Date: 2009-06-02T15:55:26-0700

[[at]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- cz
- de
- es
- fr
- it
- jp
- nl
- pl
- ro
- ru
- sk
- tr
- tw

## 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

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •