Open In App

array data() in C++ STL with Examples

The array::data() is a built-in function in C++ STL which returns an pointer pointing to the first element in the array object.

Syntax:



array_name.data()

Parameters: The function does not accept any parameters.

Return Value: The function returns an pointer.



Below programs illustrate the above function:

Program 1:




// CPP program to demonstrate the
// array::data() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
    array<int, 5> arr = { 1, 2, 3, 4, 5 };
  
    // prints the array elements
    cout << "The array elements are: ";
    for (auto it = arr.begin(); it != arr.end(); it++)
        cout << *it << " ";
  
    // Points to the first element
    auto it = arr.data();
  
    cout << "\nThe first element is:" << *it;
  
    return 0;
}

Output:
The array elements are: 1 2 3 4 5 
The first element is:1

Program 2:




// CPP program to demonstrate the
// array::data() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
    array<int, 5> arr = { 1, 2, 3, 4, 5 };
  
    // prints the array elements
    cout << "The array elements are: ";
    for (auto it = arr.begin(); it != arr.end(); it++)
        cout << *it << " ";
  
    // Points to the first element
    auto it = arr.data();
  
    // increment
    it++;
    cout << "\nThe second element is: " << *it;
  
    // increment
    it++;
    cout << "\nThe third element is: " << *it;
  
    return 0;
}

Output:
The array elements are: 1 2 3 4 5 
The second element is: 2
The third element is: 3

Article Tags :
C++