vector::front
Visual Studio 2005
Returns a reference to the first element in a vector.
reference front( ); const_reference front( ) const;
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.
// 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;
}
Reference
vector Classvector::front and vector::back
Standard Template Library
Other Resources
vector Members
Confusing sample.
That's a confusing sample -- both vars i and ii refer to the same storage: the first item in the vector. The var i is mutable, and the change to it is then seen via the immutable ii, which also happens to match the content of the 2nd item pushed to the back of the vector. The comment exacerbates this, asserting "by incrementing i, we move the the[sic] front reference to the second element." No, instead the first item in the vector is modified from 10 to 11. Evidence for the doubter can be gathered by changing the push_back(11) to push_back(14), and noting that the program still produces 10 and 11.
Juanito
Juanito
- 1/8/2011
- JuanchoPanza