Returns a reference to the element at a specified location in the vector.

reference at(
   size_type _Pos
const_reference at(
   size_type _Pos
) const;


The subscript or position number of the element to reference in the vector.

A reference to the element subscripted in the argument. If _Off is greater than the size of the vector, at throws an exception.

If the return value of at is assigned to a const_reference, the vector object cannot be modified. If the return value of at is assigned to a reference, the vector object can be modified.

// vector_at.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>

int main( )
   using namespace std;
   vector <int> v1;
   v1.push_back( 10 );
   v1.push_back( 20 );

   const int &i = 0 );
   int &j = 1 );
   cout << "The first element is " << i << endl;
   cout << "The second element is " << j << endl;
The first element is 10
The second element is 20

Header: <vector>

Namespace: std

Community Additions