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

ความแตกต่างระหว่าง std::vector และ std::array ใน C++

ทั้ง std::vector และ std::array เป็นคอนเทนเนอร์สำหรับเก็บลำดับข้อมูล แต่มีคุณสมบัติและกรณีใช้งานที่แตกต่างกันอย่างมีนัยสำคัญ

ตารางเปรียบเทียบ

คุณสมบัติstd::vectorstd::array
ขนาดไดนามิก (ขยาย/หดได้)คงที่ (Fixed at compile-time)
หน่วยความจำHeap allocationStack allocation (โดยปกติ)
Overheadมี (pointer, size, capacity)ไม่มี (zero overhead)
การเข้าถึงO(1) แต่มี indirectionO(1) โดยตรง (contiguous)
Iterator Invalidationเกิดขึ้นเมื่อ reallocateไม่เคย (ขนาดคงที่)
push_back()รองรับไม่รองรับ
resize()รองรับไม่รองรับ
Copy/AssignDeep copy (O(n))Deep copy (O(n))
C++ VersionC++98C++11

การประกาศและเริ่มต้น

// std::vector
vector<int> v1;                    // ว่าง
vector<int> v2(10);               // 10 องค์ประกอบ (ค่า 0)
vector<int> v3(10, 5);            // 10 องค์ประกอบ (ค่า 5)
vector<int> v4 = {1, 2, 3, 4, 5}; // initializer list

// std::array
array<int, 5> a1;                // ไม่ได้ initialize (ค่า indeterminate)
array<int, 5> a2 = {};           // ทั้งหมดเป็น 0
array<int, 5> a3 = {1, 2, 3};    // เหลือเป็น 0
array<int, 5> a4 = {1, 2, 3, 4, 5};

ตัวอย่างโค้ด: std::vector (2D)

#include <iostream>
#include <vector>

using namespace std;

int main() {
    // 2D vector (jagged array)
    vector<vector<int>> matrix = {
        {4, 5, 3},
        {2, 7, 6},
        {3, 2, 1, 10}  // แถวที่ 3 ยาวกว่า
    };
    
    cout << "2D Vector:" << endl;
    for (const auto& row : matrix) {
        for (int val : row) {
            cout << val << " ";
        }
        cout << endl;
    }
    
    // Dynamic resizing
    matrix.push_back({8, 9});
    matrix[0].push_back(100);
    
    return 0;
}

ตัวอย่างโค้ด: std::array

#include <iostream>
#include <array>

using namespace std;

int main() {
    array<int, 4> arr = {10, 20, 30, 40};
    
    cout << "Size: " << arr.size() << endl;
    cout << "Max size: " << arr.max_size() << endl;
    
    cout << "Elements: ";
    for (int x : arr) cout << x << " ";
    cout << endl;
    
    arr.fill(1);
    cout << "After fill(1): ";
    for (int x : arr) cout << x << " ";
    cout << endl;
    
    // 2D array (fixed size)
    array<array<int, 3>, 2> matrix = {{
        {1, 2, 3},
        {4, 5, 6}
    }};
    
    return 0;
}

คำแนะนำการเลือกใช้

สถานการณ์แนะนำ
ขนาดไม่ทราบ compile-time หรือเปลี่ยนแปลงได้std::vector
ขนาดคงที่ รู้จักตอน compile-timestd::array
ต้องการประสิทธิภาพสูงสุด (no heap alloc)std::array
ต้องการ push_back, resize บ่อยstd::vector
ส่งผ่านฟังก์ชันโดยค่า (pass by value)std::array (cheap copy สำหรับขนาดเล็ก)
Interop กับ C APIทั้งคู่ใช้ .data() ได้

สรุป

std::array เหมาะสำหรับขนาดคงที่ ต้องการประสิทธิภาพสูงสุด และ semantics แบบ value type
std::vector เหมาะสำหรับขนาดไดนามิก ต้องการ flexibility และ ease of use