บทนำ
ใน C++ ทั้ง std::set และ std::multiset เป็น Associative Container ที่เก็บข้อมูลในลำดับที่เรียงลำดับแล้ว (Sorted Order) ความแตกต่างหลักอยู่ที่การจัดการค่าซ้ำ (Duplicate Values)
ตารางเปรียบเทียบหลัก
| ลำดับ | หัวข้อ | std::set | std::multiset |
|---|---|---|---|
| 1 | นิยาม | เก็บค่าที่ไม่ซ้ำกัน (Unique Keys) เท่านั้น | เก็บค่าซ้ำได้ (Duplicate Keys Allowed) เหมาะสำหรับข้อมูลที่มีความถี่ |
| 2 | การเรียงลำดับ | ข้อมูลเรียงลำดับน้อยไปมาก | ข้อมูลเรียงลำดับน้อยไปมากเช่นกัน |
| 3 | ค่าซ้ำ | ไม่รองรับ ค่าซ้ำจะถูกละทิ้ง | รองรับค่าซ้ำได้เต็มที่ |
| 4 | การแก้ไขค่า (Manipulation) | ไม่สามารถเปลี่ยนค่าที่แทรกแล้วได้ ต้องลบแล้วแทรกใหม่ | ไม่สามารถเปลี่ยนค่าที่แทรกแล้วได้เช่นกัน |
| 5 | ฟังก์ชันนับจำนวน | ไม่มี (เพราะไม่ซ้ำ) | มี count(key) สำหรับนับจำนวนของค่านั้นๆ |
| 6 | Complexity | O(log n) สำหรับทุก operation | O(log n) สำหรับทุก operation |
ตัวอย่างโค้ด: std::set
#include <iostream>
#include <set>
using namespace std;
int main() {
int data[15] = {11, 55, 22, 66, 33, 22, 11, 44, 77, 88, 66, 99, 66, 23, 41};
set<int> my_set;
for (int i = 0; i < 15; i++) {
my_set.insert(data[i]);
}
for (auto it = my_set.begin(); it != my_set.end(); ++it) {
cout << "Item: " << *it << endl;
}
return 0;
}
ผลลัพธ์ (ไม่มีค่าซ้ำ, เรียงลำดับ)
Item: 11
Item: 22
Item: 23
Item: 33
Item: 41
Item: 44
Item: 55
Item: 66
Item: 77
Item: 88
Item: 99
ตัวอย่างโค้ด: std::multiset
#include <iostream>
#include <set>
using namespace std;
int main() {
int data[15] = {11, 55, 22, 66, 33, 22, 11, 44, 77, 88, 66, 99, 66, 23, 41};
multiset<int> my_set;
for (int i = 0; i < 15; i++) {
my_set.insert(data[i]);
}
for (auto it = my_set.begin(); it != my_set.end(); ++it) {
cout << "Item: " << *it << endl;
}
return 0;
}
ผลลัพธ์ (มีค่าซ้ำ, เรียงลำดับ)
Item: 11
Item: 11
Item: 22
Item: 22
Item: 23
Item: 33
Item: 41
Item: 44
Item: 55
Item: 66
Item: 66
Item: 66
Item: 77
Item: 88
Item: 99
สรุปการเลือกใช้
- std::set: ใช้เมื่อต้องการเก็บค่า Unique และต้องการการค้นหาแบบ Binary Search
- std::multiset: ใช้เมื่อต้องนับความถี่ (Frequency) ของข้อมูล หรือต้องเก็บข้อมูลซ้ำกันไว้หลายค่า