In C++, std::vector is a dynamic array that stores the data in the contiguous memory allocated during runtime. It internally keeps the pointer to this raw data memory. In this article, we will learn how to get std::vector pointer to the raw data.
Methods to Get Pointer to Raw Data in std::vector In C++, there are two ways to find the pointer to the raw data of a vector:
1. Get Pointer to Raw Data Using std::vector ::data() FunctionThe std::vector ::data() method is a member function of std::vector that returns a pointer to the first element of the vector. This method is available in C++11 and later.
Syntaxvector_name.data(); Example
C++
// C++ program to demonstrate accessing raw data of a vector
// using data() method
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Initialize a vector with values 1, 2, 3, 4, 5
vector<int> vec = { 1, 2, 3, 4, 5 };
// Get a pointer to the underlying array of the vector
int* ptr = vec.data();
// Output the raw data from the vector using the pointer
cout << "Raw data: ";
for (int i = 0; i < vec.size(); ++i) {
// Dereference the pointer with an offset to get
// each element
cout << *(ptr + i) << " ";
}
cout << endl;
return 0;
}
OutputRaw data: 1 2 3 4 5
Time Complexity: O(1) Space Complexity: O(1)
2. Get Pointer to Raw Vector Data Using & OperatorThe & operator can be used to get a pointer to the first element of the vector. As all the elements are the contiguous, we can get the address of the raw memory block using this method. We can use either iterator or array subscript to get the first element
Syntax&vector_name[0]
or
&*vector_name.begin() Example
C++
// C++ program to demonstrate accessing raw data of a vector
// using address of the first element
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Initialize a vector with values 1, 2, 3, 4, 5
vector<int> vec = { 1, 2, 3, 4, 5 };
// Get a pointer to the first element of the vector
int* ptr = &vec[0];
// Output the raw data from the vector using the pointer
cout << "Raw data: ";
for (int i = 0; i < vec.size(); ++i) {
// Dereference the pointer with an offset to get
// each element
cout << *(ptr + i) << " ";
}
cout << endl;
return 0;
}
OutputRaw data: 1 2 3 4 5
Time Complexity: O(1) Space Complexity: O(1)
|