Open In App

Vector data() in C++ STL

Last Updated : 21 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, the vector data() is a built-in function used to access the internal array used by the vector to store its elements. In this article, we will learn about vector data() in C++.

Let’s take a look at an example that illustrates the vector data() method:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4};

    // Accessing first element of vector v's
  	// internal array
    cout << *v.data();
  
    return 0;
}

Output
1

This article covers the syntax, usage, and common examples of vector data() method in C++:

Syntax of Vector data()

The vector data() is the member method of std::vector defined inside <vector> header file.

v.data();

Parameters

  • The function does not accept any parameters.

Return Value

  • Returns a pointer to the first element of the vector's internal array.
  • If the vector is empty, the returned pointer is not dereferenceable.

Examples of Vector data()

The following examples demonstrate how to use the vector data() method in different scenarios:

Modify Element of Given Index using data()

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4};

    int* arr = v.data();

    // Modify 1st index element to 8
    arr[1] = 8;

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
1 8 3 4 

Explanation: The changes done on the internal array where reflected in the vector.

Traverse Whole Vector Using data()

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4};

    int* arr = v.data();

    // Accessing all elements of vector
    for (int i = 0; i < v.size(); i++)
        cout << *(arr + i) << " ";
    return 0;
}

Output
1 2 3 4 

Next Article
Article Tags :
Practice Tags :

Similar Reads