#include <iostream> #include <set> using namespace std; int main () { int intArray[] = {5,4,1,3,2}; set<int> setOfInt (intArray, intArray+5); set<int>::iterator it; cout << "setOfInt contains"; for ( it=setOfInt.begin() ; it != setOfInt.end(); it++ ) cout << " " << *it; cout << endl; return 0; }The program outputs the following:
setOfInt contains 1 2 3 4 5You can change the sorting function, or the comparison function, by creating one and referencing it through a function pointer in the set’s constructor. You can find many examples online.
Function | Description |
set_union(abegin, aend, bbegin, bend, oiterator); | returns the union of range [abegin, aend) and range [bbegin, bend) |
set_intersection(abegin, aend, bbegin, bend, oiterator); | returns the intersection of range [abegin, aend) and range [bbegin, bend) |
set_difference(abegin, aend, bbegin, bend, oiterator); | returns the difference of range [abegin, aend) and range [bbegin, bend) |
A.lower_bound(k); | returns an iterator to the first element whose key is equal to or greater than k |
A.upper_bound(k); | returns an iterator to the first element whose key is greater than k |
A.insert(v); | inserts v in A |
A.insert(i, j); | inserts range [i, j] in A |
#include <iostream> #include <string> #include <set> using namespace std; ostream & operator<<(ostream & os, set<string> s) { set<string>::iterator sti; for(sti = s.begin(); sti != s.end(); sti++) os << *sti << ' '; return os; } int main() { set<string> set1, set2, set3; int i; string ts="value#"; string res; for(i=0;i<5;i++){ res=ts; res+=('a'+i); set1.insert(res); } for(i=0;i<10;i++){ res=ts; res+=('a'+i); set2.insert(res); } cout<<"set1: "<<set1<<"\nlower_bound: "<<*(set1.lower_bound("value#b"))<< "\nupper_bound: "<<*(set1.upper_bound("value#b"))<<endl; cout<<"set2: "<<set2<<endl; set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), insert_iterator<set<string> >(set3, set3.begin())); cout<<"set3: "<<set3<<endl; return 0; }As you can see from the program output, set3 covers everything set1 and set2 cover. Now that you have acquired one more powerful tool, STL, you should not be afraid to use it from now on. Use it well and it can solve many problems for you.