C++ Vector Library - back() Function



Description

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

Calling back on empty vector causes undefined behavior.

Declaration

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

C++98

reference back();
const_reference back() const;

Parameters

None

Return value

Reference to last element of the vector.

If vector object is constant qualified then method returns a constant reference otherwise 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::back() function.

#include <iostream>
#include <vector>

using namespace std;

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

   cout << "Last element of vector = " << v.back() << endl;

   return 0;
}

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

Last element of vector = 5
vector.htm
Advertisements