std::array::at()
เข้าถึงสมาชิกของ std::array พร้อมตรวจสอบขอบเขต (bounds checking) ปลอดภัยกว่า operator[]
Syntax
reference at(size_type pos); const_reference at(size_type pos) const;
พารามิเตอร์และคืนค่า
- pos: ดัชนีที่ต้องการเข้าถึง (0-based)
- คืนค่า: reference ไปยังสมาชิกที่ตำแหน่ง pos
- ข้อยกเว้น: โยน
std::out_of_rangeถ้า pos >= size()
ตัวอย่าง 1: การใช้งานปกติ
#include <iostream>
#include <array>
using namespace std;
int main() {
array<float, 4> arr = {12.1, 67.3, 45.0, 89.1};
cout << "Element at index 1: " << arr.at(1) << endl; // 67.3
cout << "Element at index 3: " << arr.at(3) << endl; // 89.1
// แก้ไขค่าได้ (คืน reference)
arr.at(1) = 100.0;
cout << "After modify: " << arr.at(1) << endl; // 100.0
return 0;
}
ตัวอย่าง 2: จับข้อยกเว้น out_of_range
#include <iostream>
#include <array>
#include <stdexcept>
using namespace std;
int main() {
array<float, 4> arr = {12.1, 67.3, 45.0, 89.1};
try {
cout << arr.at(8) << endl; // index 8 ไม่มีอยู่ (size=4)
}
catch (const out_of_range& e) {
cout << "Exception caught: " << e.what() << endl;
// output: array::at: __n (which is 8) >= _Nm (which is 4)
}
return 0;
}
เปรียบเทียบ at() vs operator[]
| คุณสมบัติ | at() | operator[] |
|---|---|---|
| Bounds checking | มี (โยน exception) | ไม่มี (undefined behavior) |
| ประสิทธิภาพ | ช้าลงเล็กน้อย | เร็วกว่า |
| ความปลอดภัย | สูง | ต่ำ |
| ใช้เมื่อ | index มาจาก input ภายนอก | index มั่นใจว่าถูกต้อง |
แนวทางปฏิบัติที่ดี
- ใช้ at() เมื่อ index มาจาก user input, file, network หรือคำนวณที่ซับซ้อน
- ใช้ operator[] ในลูปที่มั่นใจว่า index อยู่ในขอบเขต (เช่น for loop ปกติ)
- ใน Debug build บาง compiler มี bounds checking ให้ operator[] ด้วย