C++ Vector Library - front() Function



Description

The C++ function std::vector::front() returns a reference to the first element of the vector.

Declaration

Following is the declaration for std::vector::front() function form std::vector header.

C++98

reference front();
const_reference front() const;

Parameters

None

Return value

Returns constant reference if object is constant qualified otherwise returns non-constant reference.

Exceptions

This member function never throws exception.

Time complexity

Constant i.e. O(1)

Example

The following example shows the usage of std::vector::front() function.

#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v = {1, 2, 3, 4, 5};

   cout << "First element of vector = " << v.front() << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

First element of vector = 1
vector.htm
Advertisements