Am Sonntag, 6. September 2015 19:13:17 UTC+2 schrieb mark:
>
> template<class container_t_, class el_t_, class field_t_>
> void my_sort(container_t_& cnt, field_t_ el_t_::* field, bool asc) {
> std::sort(cnt.begin(), cnt.end(), [field,asc](el_t_ a, el_t_ b) {
> return asc ? a.*field < b.*field : a.*field > b.*field;
> });
> }
A couple of suggestions:
(1) Since you are now generic over the kind of container to sort, you
should probably use the non-member begin/end functions to be a
little more flexible. This way, the function will work for raw
arrays as well, for example.
(2) The signature of your lambda function is suboptimal because you
take its arguments by value which will produce unnecessary copies
which is quite costly for non-trivial types like std::string.
(3) You can avoid the "asc?:" branch by moving the check outside of
the sort function. There should not be a big difference if your
CPU does branch prediction.
So, after some tweaking I get:
template<class Cont, class Clazz, class T, class Func>
void sort_by_member_func(Cont& cnt, T Clazz::* field, Func func) {
using std::begin; // With these we can avoid the std:: later
using std::end; // which then also allows ADL to kick in.
std::sort(begin(cnt), end(cnt),
[field, &func](T const& a, T const& b) {
return func(a.*field, b.*field);
}
);
}
template<class Cont, class Clazz, class T>
void sort_by_member(Cont& cnt, T Clazz::* field, bool asc) {
if (asc) {
sort_by_member_func(cnt, field, std::less<T>());
} else {
sort_by_member_func(cnt, field, std::greater<T>());
}
}
Cheers!
SG