Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ vector::data function is used to create a pointer to the first element of the vector. The retrieved pointer can be offset to access any element of the vector.

Syntax

value_type* data() noexcept;
const value_type* data() const noexcept;

Parameters

No parameter is required.

Return Value

A pointer to the first element of the vector.

Time Complexity

Constant i.e, Θ(1).

Example:

In the below example, the vector::data function is used to create a pointer pointing to the first element of the vector MyVector. It is further used to alter other elements of the vector.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector{10, 20, 30, 40, 50};

  int* p = MyVector.data();
  cout<<"First element is: "<<*p<<"\n";
  
  p++;
  cout<<"Second element is: "<<*p<<"\n";
  
  *p = 100;  
  cout<<"Now the second element is: "<<*p<<"\n";
  
  p[3] = p[3] + 500;
  cout<<"Now the fifth element is: "<<p[3]<<"\n";  
  
  return 0;
}

The output of the above code will be:

First element is: 10
Second element is: 20
Now the second element is: 100
Now the fifth element is: 550

❮ C++ - Vector