Listing 2: A set of integers that can be sorted in increasing or decreasing
order
#include <set>
#include <algorithm>
#include <iostream>
template<class T>
struct print : public std::unary_function<T, void>
{
print(std::ostream& out) : os(out) {}
void operator() (T x) { os << x;}
std::ostream& os;
};
enum SortOrder { Increasing, Decreasing };
class fCompare
{
public:
fCompare(const SortOrder& o) : m_order(o) {}
bool operator() (const int a, const int b) const
{
if (m_order == Increasing) return a < b;
else return b < a;
}
private:
const SortOrder& m_order;
};
int main()
{
SortOrder sort_state = Increasing;
fCompare comp_obj(sort_state);
std::set<int, fCompare> IntSet(comp_obj);
for (int i = 0; i < 5; ++i)
{
IntSet.insert(i);
}
for_each(IntSet.begin(), IntSet.end(), print<int>(std::cout));
std::cout << std::endl;
sort_state = Decreasing;
for (int i = 0; i < 5; ++i)
{
IntSet.insert(i);
}
for_each(IntSet.begin(), IntSet.end(), print<int>(std::cout));
std::cout << std::endl;
}