ทั้ง std::vector และ std::array เป็นคอนเทนเนอร์สำหรับเก็บลำดับข้อมูล แต่มีคุณสมบัติและกรณีใช้งานที่แตกต่างกันอย่างมีนัยสำคัญ
ตารางเปรียบเทียบ
| คุณสมบัติ | std::vector | std::array |
|---|---|---|
| ขนาด | ไดนามิก (ขยาย/หดได้) | คงที่ (Fixed at compile-time) |
| หน่วยความจำ | Heap allocation | Stack allocation (โดยปกติ) |
| Overhead | มี (pointer, size, capacity) | ไม่มี (zero overhead) |
| การเข้าถึง | O(1) แต่มี indirection | O(1) โดยตรง (contiguous) |
| Iterator Invalidation | เกิดขึ้นเมื่อ reallocate | ไม่เคย (ขนาดคงที่) |
push_back() | รองรับ | ไม่รองรับ |
resize() | รองรับ | ไม่รองรับ |
| Copy/Assign | Deep copy (O(n)) | Deep copy (O(n)) |
| C++ Version | C++98 | C++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-time | std::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