Home »
C++ STL
vector::front(), vector::back(), vector::at() and vector::data() functions with examples | C++ STL
In this article, we will learn about some of the most useful functions like vector::front(),vector::back(), vector::at() and vector::data() of vector class in C++ STL.
Submitted by IncludeHelp, on August 24, 2018
C++ STL - vector::front(), vector::back(), vector::at() and vector::data() functions
vector::front(), vector::back(), vector::at() and vector::data() functions are the predefined function of vector class, which are used for vector element accessing in C++ STL.
1. vector::front()
Returns reference to the first element of a vector i.e. we can say it returns first element of the vector.
2. vector::back()
Returns reference to the last element of a vector i.e. we can say it returns last element of the vector.
3. vector::at(i)
Returns reference to the ith element of a vector i.e. we can say it returns ith element of the vector.
4. vector::data()
As we know, vector is a dynamic array, and it can also be accessed like an array style. vector::data() returns the direct pointer to the first element of array (used by vector in the memory) and we can access all elements.
Sample Input and Output
Input:
vector<int> num{10, 20, 30, 40, 50}
Output:
num.front(): 10
num.back(): 50
num.at(2): 30
All elements using vector::data(): 10 20 30 40 50
Example
In this example, we are demonstrating the examples of vector::front(), vector::back(), vector::at() and vector::data() functions in C++ STL:
#include <iostream>
#include <vector>
using namespace std;
int main() {
// declare vector
vector<int> num{10, 20, 30, 40, 50};
// vector::front ()
cout << "num.front(): " << num.front() << endl;
// vector::back ()
cout << "num.back() : " << num.back() << endl;
// vector::at ()
cout << "num.at(2) : " << num.at(2) << endl;
// vector::data ()
int *ptr = num.data();
cout << "All elements using vector::data () : ";
// note: there is no need to use vector iterator
for (int i = 0; i < num.size(); i++) cout << *(ptr + i) << " ";
cout << endl;
return 0;
}
Output
num.front(): 10
num.back() : 50
num.at(2) : 30
All elements using vector::data () : 10 20 30 40 50