std::list 정렬에 대하여

std::list는 std::vector와 달리 std::list가 임의 접근(random access)을 지원하지 않기 때문에 STL 알고리즘 라이브러리의 sort()를 사용할 수 없습니다.

// std::list排序示例

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <list>

// 它是个仿函数
struct mycmp {
    bool operator()(int* a, int* b) {
        return *a < *b;
    }
};

int main() {
    std::list il;
    int ia[10];

    time_t t;
    time(&t);
    srand((unsigned int)t);

    printf("Before: ");
    for( int i=0; i<10; ++i ) {
        ia[i] = rand();
        il.push_back(&ia[i]);
        printf("%d ", ia[i]);
    }
    printf("\n");

    il.sort(mycmp());

    printf("After: ");
    std::list::iterator i;
    for( i=il.begin(); i!=il.end(); ++i ) {
        printf("%d ", **i);
    }
    printf("\n");

    return 0;
}