[STL] list 정렬에서 greater를 어떻게 쓰는지..

assa의 이미지

list<char **> tlist가 있을때,

char ** 문자열 배열이 총 10개중.

5번째 문자열을 기준으로 char **을 정렬한다고 할때,

tlist.sort(.....) 에서 .....부분을 어떻게 넣어야할지 고민입니다.

어떻게 하는것이 좋을까요?

doldori의 이미지

dereference 하는 함수 개체를 하나 만들면 됩니다.

#include <functional>

struct Deref
    : public std::binary_function<char**, char**, bool>
{
    Deref(int i) : index_(i) { }
    bool operator()(char** p, char** q) const
    {
        return strcmp(p[index_], q[index_]) < 0;
    }
    int index_;
};

list<char**> tlist;
tlist.sort(Deref(4));
assa의 이미지

list.sort(Deref(4)) 할때, list의 char ** 들은 어떻게 Deref 에 input으로

들어가는 건가요?

public stdbinary_function<char **, char **, bool>

이 부분이 Deref에 input으로 받는건지...

이해가 잘 안되네요 ㅠㅠ..휴~~

doldori의 이미지

assa wrote:
list.sort(Deref(4)) 할때, list의 char ** 들은 어떻게 Deref 에 input으로

들어가는 건가요?


Deref::operator()()가 해줍니다. list::sort()가 호출할 수 있는 형태로 만들어주는 거죠.
자세한 내용은 책을 참조하세요. function object 또는 functor 부분을 보시면 됩니다.

assa wrote:
public std::binary_function<char **, char **, bool>

이 부분이 Deref에 input으로 받는건지...


이것은 binder나 adaptor에도 사용할 수 있도록 넣어준 건데 지금은 없어도 됩니다.
저는 그냥 습관적으로 사용합니다.
assa의 이미지

class 내에서 따로 struct 를 넣기가 보기 흉한 느낌이 들어서 ^^;;

따로 함수를 만들어서 쓰면 어떨까해서 input에 대해서 질문했습니다.^^;

생각해보니 그냥 class를 operator()로 해서 써도 되겠다는 생각이 들었지만,

함수로 만약 구현한다면 어떻게 input을 넣어야 할지...

예로 bool class aaaDeref(.....) 에서 .... 를 어떻게 넣어야할지..

그러면 tlist.sort(Deref(....))가 되겠지요..

궁금함만 자꾸 늘어갑니다...

doldori의 이미지

함수 개체는 상태(state)를 가질 수 있는 반면 함수를 쓰면 유연하지 못한 단점이
있긴 한데, 아무튼 이런 식으로 하면 됩니다.

class aaa
{
    static bool deref(char** p, char** q)
    {
        return strcmp(p[4], q[4]) < 0; 
    }
    void f()
    {
        list<char**> tlist;
        tlist.sort(deref); 
    }
};

함수를 쓰면서도 index를 임의로 주려면 boost::bind를 쓰면 되는데
표준이 아니기도 하고 overkill이라는 느낌도 듭니다.
#include <boost/bind.hpp>

class aaa
{
public:
    static bool deref(char** p, char** q, int index)
    {
        return strcmp(p[index], q[index]) < 0; 
    }
    void f()
    {
        using namespace boost;
        list<char**> tlist;
        tlist.sort(bind(deref, _1, _2, 4)); 
    }
};