说明: 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, 换库.