Last Updated : 11 Jul, 2025
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;
}
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.
Parametersv.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;
}
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;
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4