Set เป็นโครงสร้างข้อมูลเก็บค่าตัวเลข คุณสมบัติ: สมาชิกไม่ซ้ำกัน (distinct) และจัดเรียงจากน้อยไปมาก สามารถกำหนดชนิดข้อมูลเองได้ใน C++
ตัวอย่าง: Input: 124689781230 → Output: 1230467889 (เฉพาะค่าที่ไม่ซ้ำ เรียงลำดับ)
ตรรกะ
Set รับค่าแบบสุ่มและซ้ำได้ แต่จะเก็บเฉพาะค่าที่ไม่ซ้ำและเรียงจากน้อยไปมาก
ตัวอย่างโค้ด
#include<bits/stdc++.h>
using namespace std;
struct Test {
int id;
bool operator < (const Test& t) const {
return (this->id < t.id);
}
};
int main() {
Test t1 = { 12 }, t2 = { 45 }, t3 = { 32 }, t4 = { 78 }, t5 = {12}, t6 = {8};
set<struct Test> s;
s.insert(t1); s.insert(t2); s.insert(t3); s.insert(t4); s.insert(t5); s.insert(t6);
set<struct Test>::iterator it;
for (it = s.begin(); it != s.end(); it++) {
cout << (*it).id << " ";
}
return 0;
}
ผลลัพธ์
8 12 32 45 78