作者khoguan (Khoguan Phuann)
看板C_and_CPP
标题Re: [问题] type compare (简易版程式)
时间Mon Jun 13 03:34:12 2005
※ 引述《chun0826 (蛋头 ︩》之铭言:
: ※ 引述《khoguan (Khoguan Phuann)》之铭言:
: : 是的。list 中的 sort() 有两个,一个不需参数的就是
: : aecho哥讲的那样使用就对了,很简单。另一个要参数的,
: : 就比较复杂,我写了一个完整的程式供参考:
我真是小题大作,弄了复杂难懂的写法造成原po的困扰。
真是不好意思。以下是简单易懂版。技巧就是透过 global function
来包裹 member function。但愿能解决他的问题。
理论上,这样写执行效率会比较差一点。但若资料不是极多,
应该感觉不出来。毕竟易理解较重要。
// using function pointer for list.sort()
#include <iostream>
#include <list>
#include <iterator>
using namespace std;
class MyObj {
public:
MyObj(int i=0) : data(i) {}
bool comp(const MyObj& other) const { // 假设所用的比较函式名为 comp
if (this->data < other.data) return true;
else return false;
}
friend ostream& operator<< (ostream& os, const MyObj& my);
private:
int data;
};
ostream& operator<< (ostream& os, const MyObj& my)
{
return os << my.data;
}
// 原先的复杂写法,简单改用 global function 来做
bool mem_comp(const MyObj& a, const MyObj& b)
{
return a.comp(b);
}
int main()
{
list<MyObj> mylist;
for (int i = 9; i >= 1; --i)
mylist.push_back(MyObj(i)); // 放进 9 个元素做测试用
mylist.sort(&mem_comp); // 注意用法,不写 & 也行
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.130.208.166
※ 编辑: khoguan 来自: 218.163.154.74 (01/23 20:31)