C++,
pasted
on Oct 30:
|
#include <cstdio>
#include <list>
#include <algorithm>
typedef unsigned DWORD;
struct RECT { int left, top, right, bottom; };
//ソートするデータ
struct Hoge{
DWORD flag;
RECT rectangle;
void print() const {
printf("%u, %d, %d, %d, %d\n", flag, rectangle.left, rectangle.top, rectangle.right, rectangle.bottom);
}
};
//リストに追加する関数オブジェクト
struct AddToList {
explicit AddToList(std::list<Hoge> &list): ref_list(list) { }
void operator()(const Hoge &hoge) { ref_list.push_back(hoge); }
private:
std::list<Hoge> &ref_list;
};
//データを比較する関数オブジェクト
struct CompareHoge {
bool operator()(const Hoge &a, const Hoge &b) {
return (a.flag == b.flag)? a.rectangle.left < b.rectangle.left: a.flag < b.flag;
}
};
//データを表示する関数オブジェクト
struct PrintHoge {
PrintHoge(): n(0) { }
void operator()(const Hoge &hoge) { printf("%d : ", ++n), hoge.print(); }
private:
int n;
};
int main()
{
//データ初期化
Hoge hoge[4] = {
{10, { 0,0,100,100}},
{10, { -1,0,100,100}},
{ 8, { -1,0,100,100}},
{12, { -1,0,100,100}},
};
//リストも初期化
std::list<Hoge> list;
std::for_each(hoge, hoge+4, AddToList(list));
//配列のソート
printf("start to sort on array\n");
std::for_each(hoge, hoge+4, PrintHoge());
std::sort(hoge, hoge+4, CompareHoge());
printf("\ndone.\n");
std::for_each(hoge, hoge+4, PrintHoge());
//リストのソート
printf("\nstart to sort on list.\n");
std::for_each(list.begin(), list.end(), PrintHoge());
//std::sort(list.begin(), list.end(), CompareHoge()); //<===問題の行
printf("\ndone.\n");
std::for_each(list.begin(), list.end(), PrintHoge());
}
|
Output:
|
start to sort on array
1 : 10, 0, 0, 100, 100
2 : 10, -1, 0, 100, 100
3 : 8, -1, 0, 100, 100
4 : 12, -1, 0, 100, 100
done.
1 : 8, -1, 0, 100, 100
2 : 10, -1, 0, 100, 100
3 : 10, 0, 0, 100, 100
4 : 12, -1, 0, 100, 100
start to sort on list.
1 : 10, 0, 0, 100, 100
2 : 10, -1, 0, 100, 100
3 : 8, -1, 0, 100, 100
4 : 12, -1, 0, 100, 100
done.
1 : 10, 0, 0, 100, 100
2 : 10, -1, 0, 100, 100
3 : 8, -1, 0, 100, 100
4 : 12, -1, 0, 100, 100
|
|