C++ examples for STL:set
How to find the intersection and union of two sets.
#include <iostream> #include <string> #include <set> #include <algorithm> #include <iterator> using namespace std; void DumpClass(set<string> *myset) { set<string>::iterator iter = myset->begin(); while (iter != myset->end()) {//from w ww .ja v a 2 s. c om cout << *iter << endl; iter++; } } int main() { set<string> EnglishClass; set<string> HistoryClass; EnglishClass.insert("Z"); EnglishClass.insert("M"); EnglishClass.insert("V"); EnglishClass.insert("U"); EnglishClass.insert("C"); HistoryClass.insert("V"); HistoryClass.insert("U"); HistoryClass.insert("R"); HistoryClass.insert("O"); set<string> Union; set<string> Intersection; insert_iterator<set<string>> IntersectIterate(Intersection, Intersection.begin()); insert_iterator<set<string>> UnionIterate(Union, Union.begin()); set_intersection(EnglishClass.begin(), EnglishClass.end(), HistoryClass.begin(), HistoryClass.end(), IntersectIterate); cout << "===Intersection===" << endl; DumpClass(&Intersection); set_union(EnglishClass.begin(), EnglishClass.end(), HistoryClass.begin(), HistoryClass.end(), UnionIterate); cout << endl << "===Union===" << endl; DumpClass(&Union); return 0; }