說明: Fuck vc6 內建的 stl 庫。
問題:
struct test
{
test(int _nIndex) : nIndex(_nIndex) {}
int nIndex;
};
list<test*> aList;
按照 test::nIndex 從小到大對 aList 中的元素進行排序。
方案:
方案一, 來源於辣子雞丁. 製作一個 test* 的 wapper.
#include <list>
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
struct test
{
test(int _nIndex = 0) { nIndex = _nIndex;}
int nIndex;
};
class test_ptr
{
public:
test_ptr() : ptr_(0) {}
test_ptr(test* p) : ptr_(p) {}
public:
bool operator<(const test_ptr& x) const
{
return ptr_->nIndex < x.ptr_->nIndex;
}
void print()
{
cout << ptr_->nIndex << endl;
}
private:
test * ptr_;
};
list<test_ptr> aList;
void print()
{
list<test_ptr>::iterator pos;
for(pos = aList.begin(); pos != aList.end(); ++pos)
{
(*pos).print();
}
}
int main()
{
aList.push_back(new test(15));
aList.push_back(new test(6));
aList.push_back(new test(32));
print();
aList.sort();
print();
return 0;
}
方案二, 做一個排序介面。 一開始我用這種方法。 但他在 vc 下不能通過編譯。
// 在 Dev c++ 通過
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <list>
using namespace std;
struct test
{
test(int _nIndex = 0) { nIndex = _nIndex; }
int nIndex;
};
class test_ptr_comp
{
public:
bool operator()(const test* const & x, const test* const &y) const
{
return x->nIndex < y->nIndex;
}
};
list<test*> aList;
void print()
{
list<test*>::iterator pos;
for(pos = aList.begin(); pos != aList.end(); ++pos)
{
cout << (*pos)->nIndex << endl;
}
}
int main()
{
aList.push_back(new test(15));
aList.push_back(new test(6));
aList.push_back(new test(18));
print();
aList.sort(test_ptr_comp());
print();
system("pause");
return 0;
}
在 VC 下的 sort 函數只能支援 greater 的比較介面。fucking~~
第一種方法感覺很不友好, 而且每次都通過 wrapper 取東西。 打算 sort 用個 map 來串列資料了。
準備去打 sp6, 換庫.