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

โปรแกรม C++ สำหรับการใช้งาน Set Intersection ใน STL

Set Intersection (อินเตอร์เซกชันของเซต) ประกอบด้วยองค์ประกอบที่ซ้ำกันในทั้งสองเซตเท่านั้น องค์ประกอบที่คัดลอกมาจะมาจากเซตแรกเสมอ และทั้งสองเซตต้องเรียงลำดับมาก่อน

การดำเนินการเซตทั่วไป

  • Set Union
  • Set Intersection
  • Symmetric Set Difference
  • Set Difference

อัลกอริธึม

  1. ประกาศเวกเตอร์ v และ iterator st
  2. เรียงลำดับเซตทั้งสอง
  3. เรียก set_intersection(set1, set1+n, set2, set2+n, v.begin())
  4. ปรับขนาดเวกเตอร์และแสดงผล

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

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
    int set1[] = {5, 6, 7, 8, 9, 10};
    int set2[] = {1, 2, 3, 4, 6, 7};
    vector<int> v(10);
    vector<int>::iterator st;

    sort(set1, set1 + 6);
    sort(set2, set2 + 6);

    st = set_intersection(set1, set1 + 6, set2, set2 + 6, v.begin());
    v.resize(st - v.begin());

    cout << "The intersection between the two sets has " << v.size() << " elements: " << endl;
    for (st = v.begin(); st != v.end(); ++st)
        cout << *st << " ";
    cout << endl;

    return 0;
}

ผลลัพธ์

The intersection between the two sets has 2 elements:
6 7

สังเกต: มีเพียง 6 และ 7 เท่านั้นที่อยู่ในทั้ง set1 และ set2