Visual C++ Standard Library
vector::front

Returns a reference to the first element in a vector.

reference front( ); 
const_reference front( ) const;
Return Value

A reference to the first element in the vector object. If the vector is empty, the return is undefined.

Remarks

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

When compiling with _SECURE_SCL 1, a runtime error will occur if you attempt to access an element in an empty vector. See Checked Iterators for more information.

Example

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

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

   int& i = v1.front( );
   const int& ii = v1.front( );

   cout << "The first integer of v1 is "<< i << endl;
   i++;
   cout << "The second integer of v1 is "<< ii << endl;
}
Output

The first integer of v1 is 10
The second integer of v1 is 11
Requirements

Header: <vector>

Namespace: std

See Also

Reference

Other Resources

Tags :


Community Content

Aaron Schrader [MSFT]
i and ii refer to the same element
When i post-increments, because i and ii refer to the same element, evaluating ii at the end also gives a value of 11.

The text of the second cout should not call ii a reference to the second element. It remains a reference to the first element. This is more easily seen in the output if you change the vector to hold {10, 20}.
Tags :

Page view tracker