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
|
#include <iostream>
#include <string>
#include <algorithm>
// predicate to compare member objects of class T using CMP
template < typename T, typename MEM, typename CMP = std::less<> > struct cmp_member
{
constexpr cmp_member( MEM T::*pm, CMP cmp = CMP{} ) noexcept : pm(pm), cmp(cmp) {}
bool operator() ( const T& a, const T& b ) const { return cmp( a.*pm, b.*pm ) ; }
MEM T::*pm ;
CMP cmp ;
};
int main()
{
struct A { int v = 0 ; std::string str ; };
A seq[] { { 32, "ijk" }, { 57, "abc" }, { 12, "zzz" }, { 25, "def" }, { 21, "pqr" } } ;
const auto print_seq = [&] () { for( A& a : seq ) std::cout << '{' << a.v << ',' << a.str << "} " ; std::cout << '\n' ; };
std::cout << " unsorted: " ;
print_seq() ;
std::cout << " sort on A::v: " ;
std::sort( std::begin(seq), std::end(seq), cmp_member{ &A::v } ) ;
print_seq() ;
std::cout << " sort on A::str: " ;
std::sort( std::begin(seq), std::end(seq), cmp_member{ &A::str } ) ;
print_seq() ;
std::cout << " sort on A::v (descending): " ;
std::sort( std::begin(seq), std::end(seq), cmp_member{ &A::v, std::greater<>{} } ) ;
print_seq() ;
}
|