You can override the default comparator by specializing std::less like this:
struct mytype {
int x;
};
template <>
struct std::less<mytype*>
: public binary_function<mytype*, mytype*, bool>
{ bool operator()(const mytype* _Left, const mytype* _Right) const
{ return (_Left->x < _Right->x);
}
};
I've tested this successfully using this code:
void foo() {
std::set<mytype*> s;
mytype arr[3];
arr[0].x = 3;
arr[1].x = 1;
arr[2].x = 2;
s.insert(&arr[2]); s.insert(&arr[0]); s.insert(&arr[1]); std::for_each(s.begin(), s.end(), [](const mytype* p) {
std::cout << p->x << std::endl;
});
}
The output is "1,2,3." As you can see, neither the order of elements by address, nor the order of input corresponds to that output, instead it's the
less
override.