std::array (C++11) là container bao bọc mảng C-style kích thước cố định, cung cấp interface STL (iterator, size(), at(), front(), back()...) an toàn và tiện lợi.
Đặc điểm chính
- Kích thước cố định tại compile-time – template parameter thứ 2.
- Lưu trữ trên stack (như mảng thường), không cấp phát heap.
- Hỗ trợ
begin(),end(),size(),at()(check bounds),front(),back(),fill(),swap(). - Có thể dùng với thuật toán STL (
sort,find,...).
Mã nguồn demo menu tương tác
#include <iostream>
#include <array>
#include <cstdlib>
using namespace std;
int main() {
array<int, 7> a; // mảng 7 int, chưa khởi tạo (giá trị rác)
array<int, 7>::iterator it;
int choice, val;
int cnt = 0; // số phần tử đã chèn
a.fill(0); // khởi tạo 0
while (true) {
cout << "1. Size of the array\n"
<< "2. Insert Element into the Array\n"
<< "3. Front Element\n"
<< "4. Back Element\n"
<< "5. Display elements\n"
<< "6. Exit\n"
<< "Enter your Choice: ";
cin >> choice;
switch (choice) {
case 1: cout << "Size: " << a.size() << endl; break;
case 2:
if (cnt >= a.size()) { cout << "Array full!\n"; break; }
cout << "Enter value: "; cin >> val;
a.at(cnt++) = val; // an toàn: at() check bounds
break;
case 3: cout << "Front: " << a.front() << endl; break;
case 4: cout << "Back: " << a.back() << endl; break;
case 5:
for (it = a.begin(); it != a.end(); ++it)
cout << *it << ' ';
cout << endl;
break;
case 6: return 0;
default: cout << "Wrong Choice\n";
}
}
}
Kết quả chạy
1. Size of the array 2. Insert Element into the Array 3. Front Element of the Array 4. Back Element of the Array 5. Display elements of the Array 6. Exit Enter your Choice: 1 Size of the Array: 7 Enter your Choice: 2 Enter value to be inserted: 7 ... Enter your Choice: 5 7 6 5 4 3 2 1
Khởi tạo hiện đại (C++11/17/20)
// Aggregate initialization
array<int, 5> a1 = {1, 2, 3, 4, 5};
array<int, 5> a2 {1, 2, 3, 4, 5}; // C++11 uniform init
array a3 = {1, 2, 3, 4, 5}; // C++17 CTAD (class template argument deduction)
// to_array (C++20)
auto a4 = std::to_array({1, 2, 3, 4, 5}); // array<int,5>
So sánh std::array vs std::vector vs mảng C
| Đặc điểm | std::array | std::vector | C-array T[N] |
|---|---|---|---|
| Kích thước | Cố định (compile-time) | Động (runtime) | Cố định |
| Bộ nhớ | Stack (thường) | Heap | Stack/Global |
| Biết size | .size() | .size() | sizeof/sizeof[0] |
| Bounds check | .at() | .at() | Không |
| Assign | Copy toàn bộ (O(N)) | Copy/pointer (O(N)) | Không (con trỏ) |
| STL ready | Có | Có | Có (con trỏ) |
Khi nào dùng std::array?
- Kích thước biết trước, không đổi (ma trận 3x3, buffer nhỏ, lookup table).
- Cần hiệu năng stack, tránh heap allocation.
- Thay thế mảng C cũ cho an toàn, hiện đại.