Some basic operations for set.
#include<iostream>
#include<set>
using namespace std;
int main(){
int a[] = {5, 3, 9, 3, 7, 2, 9, 3};
set<int> s(a, a+sizeof(a)/sizeof(int));
set<int>::iterator itr = s.begin();
while(itr!=s.end()){
cout << *itr << endl;
itr++;
}
pair<set<int>::iterator, set<int>::iterator> setrange;
setrange = s.equal_range(3);
itr = setrange.first;
while(itr!=setrange.second){
cout << *itr << endl;
itr++;
}
int ncount = s.count(3);
cout << "Number of 3: " << ncount << endl;
return 0;
}
The more complicated example is as follows
#include<iostream>
#include<set>
#include<string>
using namespace std;
class Student{
private:
int NO;
string Name;
public:
Student(int NO_, string Name_):NO(NO_),Name(Name_){}
int getNO() const { return NO; }
string getName() const { return Name; }
bool operator<(const Student& s) const {
return this->getNO() < s.getNO();
}
void print() const {
cout << this->getNO() << "\t" << this->getName() << endl;
}
};
template<class T, class Pred=less<T>, class A=allocator<T> >
class eset : public set<T, Pred, A>{
public:
void add(eset& second){
typedef typename set<T>::iterator setIterator;
setIterator itr = second.begin();
while(itr!=second.end()){
insert(*itr);
itr++;
}
}
void intersection(eset& second){
set<T> mid;
typedef typename set<T>::iterator setIterator;
setIterator itr = set<T, Pred, A>::begin();
while(itr!=set<T, Pred, A>::end()){
if(second.find(*itr) != second.end()){
mid.insert(*itr);
}
itr++;
}
set<T, Pred, A>::swap(mid);
}
void difference(eset& second){
set<T> mid;
typedef typename set<T>::iterator setIterator;
setIterator itr = set<T, Pred, A>::begin();
while(itr!=set<T, Pred, A>::end()){
if(second.find(*itr) == second.end()){
mid.insert(*itr);
}
itr++;
}
set<T, Pred, A>::swap(mid);
}
void show(){
typedef typename set<T>::iterator setIterator;
setIterator itr = set<T, Pred, A>::begin();
while(itr!=set<T, Pred, A>::end()){
itr->print();
itr++;
}
}
};
int main(){
Student s1(1001, "Tim");
Student s2(1002, "Sam");
Student s3(1003, "David");
eset<Student> m1;
eset<Student> m2;
m1.insert(s1);
m1.insert(s2);
m2.insert(s1);
m2.insert(s3);
cout << "m1: " << endl;
m1.show();
cout << "m2: " << endl;
m2.show();
m1.add(m2);
cout << "After Combination: " << endl;
m1.show();
return 0;
}
Note that we need to add a
const
qualifer to all member functions of
Student class. Objects in an
std::set
are necessarily
const
, since they are used as keys. When an object (or reference) is constant, you can only call member functions of that object which are declared with the
const
qualifier.