제가 알고 있는 c의 sort, std:: sort 함수에 대해서 함수포인터, 함수자(functor), 그리고 람다표현으로 그냥 예제 함 만들어 보았습니다.
#include <algorithm>
#include <functional>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compareC (const char* c1, const char* c2){ return (*c1 < *c2)? 1: (*c1 > *c2) ? -1 : 0; }
int compareS (const char& c1, const char& c2) { return (c1 < c2); }
template<class T>
struct compareF { int operator()(const T& c1, const T& c2) { return (c1 > c2); } };
int main()
{
{
char msg[] = "Hello world";
printf("\nC-sorting: Qsort-------------------------------------------------------\n");
qsort(&msg[0], strlen(msg), sizeof(char), (int (*)(const void *, const void *))compareC);
printf("%s\n", msg);
}
{
char msg[] = "welcome to todayhumor";
printf("\nstd-sorting with function ---------------------------------------------\n");
char* bgn = &msg[0];
char* end = &msg[strlen(msg)];
std::sort(bgn, end, compareS);
printf("%s\n", msg);
}
{
char msg[] = "c++ functor is difficult but very cool.";
printf("\nstd-sorting with functor ---------------------------------------------\n");
char* bgn = &msg[0];
char* end = &msg[strlen(msg)];
std::sort(bgn, end, compareF<int>());
printf("%s\n", msg);
}
{
char msg[] = "c++ goes to complete the abstraction of language as having a lambda expression.";
printf("\nstd-sorting with lambda ---------------------------------------------\n");
char* bgn = &msg[0];
char* end = &msg[strlen(msg)];
std::sort(bgn, end, [](const char& c1, const char& c2)->int{ return (c1 < c2); });
printf("%s\n", msg);
}
return 0;
}