दो सेट का इंटरसेक्शन केवल उन तत्वों द्वारा बनता है जो दोनों सेट में कॉमन होते हैं। फंक्शन द्वारा कॉपी किए गए तत्व हमेशा पहले सेट से उसी क्रम में आते हैं। दोनों सेट में तत्व पहले से क्रमबद्ध होने चाहिए।
सामान्य सेट ऑपरेशन हैं:
- Set Union
- Set Intersection
- Symmetric Set Difference या Exclusive-OR
- Set Difference या Subtraction
एल्गोरिदम
Begin
सेट वेक्टर v और इटरेटर st घोषित करें।
st = set_intersection(set1, set1 + n, set2, set2 + n, v.begin()) इनिशियलाइज़ करें।
दो सेट के बीच इंटरसेक्शन को प्रिंट करें।
End.
उदाहरण कोड
#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 set has " << (v.size()) << " elements: " << endl;
for (st = v.begin(); st != v.end(); ++st)
cout << *st << " ";
cout << endl;
return 0;
}
आउटपुट
The intersection between the two set has 2 elements: 6 7