1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| template<typename T, typename R = bool>
struct sorter
{
enum pred {
box_asc = 0
,box_desc // = 1
};
typedef std::tr1::function<R (T, T)> pred_type;
static pred_type table[];
static pred_type lookup(unsigned int index);
};
template<typename T, typename R>
typename sorter<T, R>::pred_type sorter<T,R>::table[]
= {
std::less<T>() // une seule entrée
};
template<typename T, typename R>
typename sorter<T, R>::pred_type sorter<T, R>::lookup(unsigned int index)
{
typedef typename sorter<T, R>::pred_type pred_type;
static unsigned int count = sizeof(sorter<T, R>::table)/sizeof(pred_type);
return index >= count
//ici le modulo
? pred_type(std::binary_negate<pred_type>(sorter<T, R>::table[index%count]))
: sorter<T, R>::table[index];
}
int main()
{
std::vector<int> m_internal;
m_internal.push_back(3);
m_internal.push_back(4);
m_internal.push_back(2);
m_internal.push_back(1);
typedef sorter<int> sortint;
sortint::table;
int m_flag = sortint::box_asc; // index = 0 --> std::less
std::stable_sort(m_internal.begin(), m_internal.end()
,sortint::lookup(m_flag));
// echo
std::copy(m_internal.begin(), m_internal.end()
,std::ostream_iterator<int>(std::cout,","));
// volontairement out of bound
m_flag = sortint::box_desc; // index = 1 --> !std::less
std::stable_sort(m_internal.begin(), m_internal.end()
,sortint::lookup(m_flag));
// echo
std::copy(m_internal.begin(), m_internal.end()
,std::ostream_iterator<int>(std::cout,","));
return 0;
} |
Partager