For example, I want to write overload functions for set_difference which compares the type std::set<point>
class myIter : public std::iterator<std::input_iterator_tag, int> {
public:
myIter(int n) : num(n){}
myIter(const myIter & n) : num(n.num){}
int & operator *(){return num;}
myIter & operator ++(){++num; return *this;}
bool operator !=(const myIter & n){return n.num != num;}
private:
int num;
};
struct point
{
point(int X, int Y):x(X), y(Y){}
int x;
int y;
}
int main()
{
set <point> myset;
myset.insert(point(1, 1);
myset.insert(point(3, 2);
myset.insert(point(5, 3);
//find the missing elements in set for `point.x` using `set_difference`
std::set<int> missing;
std::set_difference(myIter(myset.begin()->x+1), myIter(myset.rbegin()->x),
myset.begin(), myset.end(), std::insert_iterator<std::set<int>>(missing, missing.begin()));
}
After applying the std::set_difference on point.x variables the set<int> missing must be:
missing[0] {2}
missing[1] {4}
How do i know how to write the overload operators for the operation?
Firstly,
std::set<point>requires thatpointis less-than-comparable. You can either defineoperator<forpoint, or provide a separate function object that does the comparison as the second template parameterstd::set<point,MyCompare>.Once you actually have your elements in the set, you can use
set_difference. It’s worth noting thatset_differencedoesn’t actually require you to usestd::setfor your input — you could just use a vector and thus avoid having to provide the comparison function.To use
set_difference, you will need to ensure that thevalue_types of the two iterator ranges are the same, so you’ll need another iterator wrapper that returns just thexportion of thepointvalues for the second range.