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

โปรแกรม C++ Insert Delete Find ด้วย Set STL


สมมติว่าเราใช้ set เก็บจำนวนเต็ม รับ n คิวรี แต่ละคิวรี 2 ค่า: type และ element type 1 = insert, type 2 = delete, type 3 = search (พิมพ์ Yes/No)

เช่น n = 7, queries = [[1,5],[1,8],[1,3],[2,8],[1,9],[3,8],[3,3]] ผลลัพธ์: [No, Yes]

ขั้นตอนการแก้ปัญหา

  • สร้าง set<int> s และ iterator it
  • q := จำนวนคิวรี
  • วนลูป q ครั้ง:
    • อ่าน qt, x
    • switch(qt): case 1: s.insert(x); case 2: s.erase(x); case 3: it=s.find(x); ถ้า it==s.end() พิมพ์ No ไม่อยู่พิมพ์ Yes

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

#include <iostream> #include <set> using namespace std; int main(){    set<int> s;    set<int>::iterator it;    int q,x, qt;    cin >> q;    while(q--){       cin>>qt>>x;       switch(qt){         case 1:s.insert(x); break;         case 2:s.erase(x); break;         case 3:it=s.find(x); if(it==s.end()) cout<<"No"<<endl; else cout<<"Yes"<<endl; break; } } }

อินพุต

7 1 5 1 8 1 3 2 8 1 9 3 8 3 3

เอาต์พุต

No Yes