Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน array::data() ใน C++ STL

std::array::data()

คืนค่า Pointer ชี้ไปยังสมาชิกแรกของ std::array ใช้สำหรับเข้าถึงหน่วยความจำแบบดิบ (raw memory) หรือส่งต่อให้ C-style API

Syntax

pointer data() noexcept;
const_pointer data() const noexcept;

คุณสมบัติ

  • ไม่มีพารามิเตอร์
  • คืนค่า pointer ไปยัง element แรก (index 0)
  • ถ้าอาร์เรย์ว่าง คืนค่า pointer ที่ไม่ได้ชี้ข้อมูลที่ถูกต้อง (แต่ไม่เป็น nullptr)
  • Noexcept guarantee

ตัวอย่าง 1: เข้าถึงสมาชิกแรก

#include <iostream>
#include <array>
using namespace std;

int main() {
    array<float, 4> percentage = {45.2, 89.6, 99.1, 76.1};
    
    cout << "Elements: ";
    for (auto it = percentage.begin(); it != percentage.end(); ++it)
        cout << *it << " ";
    
    auto ptr = percentage.data();
    cout << "\nFirst element via data(): " << *ptr; // 45.2
    
    return 0;
}

ตัวอย่าง 2: ใช้ pointer arithmetic เดินผ่านอาร์เรย์

#include <iostream>
#include <array>
using namespace std;

int main() {
    array<float, 4> percentage = {45.2, 89.6, 99.1, 76.1};
    
    auto ptr = percentage.data();
    cout << "First: " << *ptr << endl;      // 45.2
    cout << "Second: " << *(ptr + 1) << endl; // 89.6
    cout << "Third: " << *(ptr + 2) << endl;  // 99.1
    
    // ส่งให้ C-style function
    void cFunction(float* arr, int size);
    cFunction(percentage.data(), percentage.size());
    
    return 0;
}

การประยุกต์ใช้จริง

  • ส่งต่อให้ legacy C API ที่รับ pointer
  • ใช้กับ OpenGL, CUDA, หรือ library ต่างๆ ที่ต้องการ contiguous memory
  • การ copy memory ด้วย memcpy/memmove

ข้อควรระวัง

  • Pointer ที่ได้ invalidate เมื่ออาร์เรย์ถูกย้าย (move) หรือทำลาย
  • ไม่ควรเก็บ pointer ไว้นานเกินอายุของอาร์เรย์
  • std::vector ก็มี .data() คล้ายกัน