C++ <vector> data function
datais a very special function in vector, itReturns a pointer to the underlying array., allowing you to use vector like a C array.
datais a member function of container classes, used toreturns a pointer to the container's internal data storage. This enables vector to interoperate with C-style APIs or other code that requires raw pointers.
dataprovides a bridge between vector and C language code, reflecting vector's powerful compatibility.
Word Definitions: datameans "data", indicating obtaining a pointer to the underlying data.
Basic syntax and parameters
datais a member function of the container class, and calling it requires no parameters.
Syntax format
T* data(); const T* data() const;
Parameter description
- Parameter: No parameters
datatakes no arguments.
Function description
- Return Value: Returns a pointer to the underlying arrayPointer. If the container is const, it returns a const pointer.
- Effect: The returned pointer points to the first element of the container, equivalent to
&operator[](0)。 - Note: If the container is empty, the returned pointer is undefined (but usually not a null pointer).
Example
Let us thoroughly master through a series of examplesdataUsage.
Example 1: Basic usage - obtaining the underlying array pointer
Example
#include <vector>
int main() {
// 1. Create a vector
std::vector<int> numbers = {10, 20, 30, 40, 50};
std::cout << "The size of the vector is: " << numbers.size() << std::endl;
// 2. Use data to get the underlying array pointer
int* ptr = numbers.data();
std::cout << "Access through pointer: " << std::endl;
for(size_t i = 0; i < numbers.size(); ++i) {
std::cout << "ptr[" << i << "] = " << ptr[i] << std::endl;
}
return 0;
}
Expected output:
vector的大小是: 5 通过指针访问: ptr[0] = 10 ptr[1] = 20 ptr[2] = 30 ptr[3] = 40 ptr[4] = 50
Code analysis:
numbers.data()Returns a pointer to the first element.- Through the returned pointer, all elements can be accessed using array subscript syntax.
Example 2: Modifying elements through a pointer
dataThe returned pointer can be used to modify elements.
Example
#include <vector>
int main() {
std::vector<int> numbers = {10, 20, 30};
std::cout << "Before modification: ";
for(int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
// Get the pointer through data() and modify elements
int* ptr = numbers.data();
ptr[0] = 100;
ptr[1] = 200;
ptr[2] = 300;
std::cout << "After modification: ";
for(int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
Expected output:
修改前: 10 20 30 修改后: 100 200 300
Code analysis:
- Through
data()The returned pointer can directly modify the internal data of the vector.
Example 3: Interacting with C-style APIs
dataOne of its main uses is to interact with C functions that require array pointers.
Example
#include <vector>
#include <cstring> // for memset
// A hypothetical C-style function that computes the sum of an array
int sumArray(const int* arr, size_t size) {
int sum = 0;
for(size_t i = 0; i < size; ++i) {
sum += arr[i];
}
return sum;
}
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Use data() to pass the vector to a C-style function
int total = sumArray(numbers.data(), numbers.size());
std::cout << "Array elements: ";
for(int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
std::cout << "Sum: " << total << std::endl;
return 0;
}
Expected output:
数组元素: 1 2 3 4 5 总和: 15
Code analysis:
numbers.data()Pass the vector's internal array pointer to functions acceptingconst int*of the function.- This demonstrates vector's ability to seamlessly interact with C code.
Example 4: Using memset to manipulate memory
Can be accessed throughdata()Directly manipulate the vector's underlying memory.
Example
#include <vector>
#include <cstring> // for memset
int main() {
std::vector<int> numbers = {10, 20, 30, 40, 50};
std::cout << "Before clearing: ";
for(int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
// Use memset to set all bytes to 0
// Note: This only works for integer types; complex types may have problems
std::memset(numbers.data(), 0, numbers.size() * sizeof(int));
std::cout << "After clearing: ";
for(int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
Expected output:
清零前: 10 20 30 40 50 清零后: 0 0 0 0 0
Code analysis:
data()Allows direct manipulation of the vector's underlying memory.- Usage
memsetYou can quickly set all elements to zero. - Note: This method is not applicable to object types that have constructors.
Example 5: Safe use of the returned pointer
When the vector's memory is reallocated, previously obtained pointers become invalid.
Example
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3};
// Get the data pointer
int* ptr = numbers.data();
std::cout << "Value pointed to by the raw pointer: " << *ptr << std::endl;
// Adding elements may cause memory reallocation
numbers.push_back(4);
numbers.push_back(5);
numbers.push_back(6);
numbers.push_back(7);
numbers.push_back(8);
numbers.push_back(9);
numbers.push_back(10);
// Warning: ptr may already be invalid!
// In modern implementations, it is usually not reallocated, but you should not rely on that.
std::cout << "Value pointed to by data() after adding an element: " << *(numbers.data()) << std::endl;
// Safe practice: obtain a new pointer with data() each time.
ptr = numbers.data();
std::cout << "After re-obtaining the pointer: " << *ptr << std::endl;
return 0;
}
Code analysis:
- When the vector's capacity is insufficient,
push_backThis will cause memory reallocation. - After reallocation, the original
data()the returned pointer becomes invalid (becomes a dangling pointer). - Safe practice: call it again every time you use it.
data(), or usereserve()Pre-allocate enough space.
other extensions