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

Set vs Map ใน C++ STL

Set เป็นชนิดข้อมูลนามธรรม (Abstract Data Type) ที่สมาชิกทุกตัวต้องไม่ซ้ำกัน เพราะค่าของสมาชิกระบุตัวตนได้ ค่าไม่สามารถแก้ไขได้หลังเพิ่มเข้า Set แต่วางได้ว่าจะลบและเพิ่มค่าที่ปรับเปลี่ยนแล้ว

Map เป็น Container แบบ Associative จัดเก็บสมาชิกในรูปแบบ Key-Value แต่ละสมาชิกมี Key และ Mapped Value ไม่มี Mapped Value สองตัวที่มี Key เหมือนกัน

สรุป: Set มีแค่ Key, Map มี Key และ Value ทั้งคู่ ต้องไม่ซ้ำและเรียงลำดับ สำหรับข้อมูลไม่เรียงมี unordered_set/unordered_map, multiset/multimap

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

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

int main() {
    set<int> s; set<int>::iterator it;
    s.insert(7); s.insert(6); s.insert(1); s.insert(4);
    s.insert(2); s.insert(9); s.insert(10);
    cout << "Elements are in set:\n";
    for (auto it : s) cout << it << " ";
    return 0;
}

ผลลัพธ์

1 2 4 6 7 9 10

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

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

int main() {
    map<char, int> m; map<char, int>::iterator iter;
    m.insert(pair<char, int>('a', 10));
    m.insert(pair<char, int>('b', 20));
    cout << "Elements in map:\n";
    for (iter = m.begin(); iter != m.end(); iter++)
        cout << "[ " << iter->first << ", " << iter->second << "]\n";
    return 0;
}

ผลลัพธ์

Elements in map:
[ a, 10]
[ b, 20]