Array data() in C++ STL with Examples


The array is a collection of elements of the same data type stored in continuous memory locations.

C++ standard library contains many libraries that support the functioning of arrays. One of them is an array data() method.

The array data() in c++ returns a pointer pointing to the first element of the object.

Syntax

array_name.data();

Parameter

There are no parameters accepted by the function.

Return type

A pointer to the first element of the array.

Example

Program To Illustrate The Use Of Array Data() Method −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   array<float, 4> percentage = { 45.2, 89.6, 99.1, 76.1 };
   cout << "The array elements are: ";
   for (auto it = percentage.begin(); it != percentage.end(); it++)
   cout << *it << " ";
   auto it = percentage.data();
   cout << "\nThe first element is:" << *it;
   return 0;
}

Output

The array elements are: 45.2 89.6 99.1 76.1
The first element is:45.2

Example

Program To Illustrate The Use Of Array Data() Method

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   array<float, 4> percentage = { 45.2, 89.6, 99.1, 76.1 };
   cout << "The array elements are: ";
   for (auto it = percentage.begin(); it != percentage.end(); it++)
   cout << *it << " ";
   auto it = percentage.data();
   it++;
   cout << "\nThe second element is: " << *it;
   it++;
   cout << "\nThe third element is: " << *it;
   return 0;
}

Output

The array elements are: 45.2 89.6 99.1 76.1
The second element is: 89.6
The third element is: 99.1

Updated on: 24-Oct-2019

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements