在 C++ 中,data()
函數(shù)通常與容器(如 std::vector
, std::string
, std::array
等)一起使用,以獲取指向容器內(nèi)部數(shù)據(jù)的指針
#include<iostream>
#include<vector>
int main() {
// 創(chuàng)建一個包含整數(shù)的 std::vector
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 使用 data() 函數(shù)獲取指向內(nèi)部數(shù)據(jù)的指針
int* data_ptr = numbers.data();
// 輸出數(shù)據(jù)
for (size_t i = 0; i< numbers.size(); ++i) {
std::cout << "Element " << i << ": " << *(data_ptr + i)<< std::endl;
}
return 0;
}
在這個例子中,我們首先創(chuàng)建了一個包含整數(shù)的 std::vector
。然后,我們使用 data()
函數(shù)獲取指向內(nèi)部數(shù)據(jù)的指針。最后,我們遍歷并輸出數(shù)據(jù)。
請注意,data()
函數(shù)返回的指針可能會在容器發(fā)生修改時失效。因此,在使用指針之前,請確保容器沒有發(fā)生修改。