溫馨提示×

如何使用c++中的data函數(shù)獲取數(shù)據(jù)

c++
小樊
81
2024-09-15 17:21:50
欄目: 編程語言

在 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ā)生修改。

0