It would be easiest if you could use the default comparison function, that is the operator<. Note that pointers can be compared with < but most likely it is not what you need.
If you need to use a different comparison function / function object, typedef's can help (because the set would otherwise have very long template arguments. With a user-defined function it might look like this:
Code:
bool compare(int a, int b)
{
return b < a;
}
int main()
{
typedef std::set<int, bool(*)(int, int)> IntSet;
IntSet s(compare);
...
}
If you have sets of different kinds it might also help to templatize the functions that work on sets.
Code:
#include <iostream>
#include <set>
#include <cstdlib>
bool descending(int a, int b)
{
return b < a;
}
//this function works on any kind of set (ignoring the allocator)
template <class Key, class Compare>
void print_set(const std::set<Key, Compare>& s)
{
for (typename std::set<Key, Compare>::const_iterator it = s.begin(); it != s.end(); ++it)
std::cout << *it << ' ';
std::cout << '\n';
}
int main()
{
typedef std::set<int, bool(*)(int, int)> IntSet;
IntSet s1(descending);
//another set uses default for comparison
std::set<int> s2;
for (int i = 0; i != 20; ++i) {
int r = rand() % 32;
s1.insert(r);
s2.insert(r);
}
//same function can handle both sets
print_set(s1);
print_set(s2);
}