vector::data() function with example in C++ STL

C++ STL vector::data() function: Here, we are going to learn about the data() function of vector header in C++ STL with example.
Submitted by IncludeHelp, on May 15, 2019

C++ vector::data() function

vector::data() is a library function of "vector" header, it is used to access the vector elements, it returns a pointer to the memory array used by the internally by the vector to store the elements.

Note: To use vector, include <vector> header.

Syntax of vector::data() function

    vector::data();

Parameter(s): none – It accepts nothing.

Return value: value_type* – It returns a pointer to the first element in the array used internally by the vector.

Example:

    Input:
    vector<int> vector1{ 1, 2, 3, 4, 5 };
    
    //declare a pointer of same type
    int* ptr = vector1.data();
    
    Accessing elements:
    cout << *ptr << endl;
    ptr++;
    cout << *ptr << endl;

    Output:
    1
    2

C++ program to demonstrate example of vector::data() function

//C++ STL program to demonstrate example of
//vector::data() function

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v1{ 10, 20, 30, 40, 50 };

    //declare a pointer of same type
    int* ptr = v1.data();

    //printing all elements
    //using vector::data() function
    cout << "all elements of vector v1..." << endl;
    for (int i = 0; i < v1.size(); i++) {
        cout << "element at index " << i << " : " << *ptr << endl;
        //increasing pointer
        ptr++;
    }

    //updating some elements
    //initializing the pointer again
    ptr = v1.data();
    *(ptr + 0) = 100;
    *(ptr + 1) = 200;
    *(ptr + 2) = 300;

    //after updating, printing all elements
    //using vector::data() function
    cout << "all elements of vector v1..." << endl;
    for (int i = 0; i < v1.size(); i++) {
        cout << "element at index " << i << " : " << *ptr << endl;
        //increasing pointer
        ptr++;
    }

    return 0;
}

Output

all elements of vector v1...
element at index 0 : 10
element at index 1 : 20
element at index 2 : 30
element at index 3 : 40
element at index 4 : 50
all elements of vector v1...
element at index 0 : 100
element at index 1 : 200
element at index 2 : 300
element at index 3 : 40
element at index 4 : 50

Reference: C++ vector::data()


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.