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

ตรวจสอบ Key ใน C++ Map และ Unordered_Map

Map และ Unordered Map ใช้ค้นหา Key ด้วย find(key) คืน Iterator หากเจอ, คืน end() หากไม่เจอ

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

#include <iostream>
#include <map>
using namespace std;

string isPresent(map m, string key) {
    if (m.find(key) == m.end())
        return "Not Present";
    return "Present";
}

int main() {
    map my_map;
    my_map["first"] = 4;
    my_map["second"] = 6;
    my_map["third"] = 6;

    string check1 = "fifth", check2 = "third";

    cout << check1 << ": " << isPresent(my_map, check1) << endl;
    cout << check2 << ": " << isPresent(my_map, check2);

    return 0;
}

ผลลัพธ์

fifth: Not Present
third: Present

วิธีอื่นๆ

// 1. ใช้ count() - คืน 0 หรือ 1 (Map ไม่มีค่าซ้ำ)
if (my_map.count("third")) { ... }

// 2. ใช้ contains() (C++20)
if (my_map.contains("third")) { ... }

// 3. Unordered_map ใช้วิธีเดียวกัน (เร็วกว่าเฉลี่ย O(1))
unordered_map umap;
umap["key"] = 100;
if (umap.find("key") != umap.end()) { ... }

Map vs Unordered_Map

คุณสมบัติmapunordered_map
ลำดับเรียงตาม Keyไม่เรียง
ค้นหาO(log n)O(1) เฉลี่ย
ใช้เมื่อต้องการเรียงลำดับต้องการความเร็วสูงสุด