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

ฟังก์ชัน map::at() ใน C++ STL


ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::at() ใน C++ STL

Map ใน C++ STL คืออะไร?

Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value โดยจัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน เข้าถึง Value ผ่าน Key ได้

map::at() คืออะไร?

map::at() เป็นฟังก์ชันใน header <map> ใช้เข้าถึง Value ของ Key ที่ระบุ คืนค่า Reference ไปยัง Value นั้น

สำคัญ: หาก Key ไม่มีอยู่ใน Map จะโยน Exception out_of_range (ต่างจาก operator[] ที่จะสร้าง Key ใหม่ถ้าไม่มี)

Syntax

map_name.at(key& k);

Parameters

k − Key ที่ต้องการค้นหา

Return Value

Reference ไปยัง Value ที่เกี่ยวข้องกับ Key k

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<int, int> TP_1;
    map<int, int> TP_2;
    
    TP_1[1] = 10;
    TP_1[2] = 20;
    TP_1[3] = 30;
    TP_1[4] = 40;
    
    TP_2[5] = 50;
    TP_2[6] = 60;
    TP_2[7] = 70;
    
    cout << "Elements at TP_1[1] = " << TP_1.at(1) << endl;
    cout << "Elements at TP_1[2] = " << TP_1.at(2) << endl;
    cout << "Elements at TP_1[3] = " << TP_1.at(3) << endl;
    cout << "\nElements at TP_2[7] = " << TP_2.at(7) << endl;
    cout << "Elements at TP_2[5] = " << TP_2.at(5) << endl;
    
    return 0;
}

ผลลัพธ์

Elements at TP_1[1] = 10
Elements at TP_1[2] = 20
Elements at TP_1[3] = 30
Elements at TP_2[7] = 70
Elements at TP_2[5] = 50

ตัวอย่างการจัดการ Exception

try {
    cout << TP_1.at(99); // Key ไม่มีอยู่
} catch (const out_of_range& e) {
    cout << "Key not found: " << e.what();
}