作者khoguan (Khoguan Phuann)
看板C_and_CPP
标题Re: [问题] type compare (简易版程式)
时间Mon Aug 15 16:53:01 2005
※ 引述《khoguan (Khoguan Phuann)》之铭言:
: ※ 引述《chun0826 (蛋头 ︩》之铭言:
: 我真是小题大作,弄了复杂难懂的写法造成原po的困扰。
: 真是不好意思。以下是简单易懂版。技巧就是透过 global function
: 来包裹 member function。但愿能解决他的问题。
: 理论上,这样写执行效率会比较差一点。但若资料不是极多,
: 应该感觉不出来。毕竟易理解较重要。
原po的问题是:
在一个 list container 中放了一些物件(假设 type 为 class MyObj),
class MyObj 本身已经提供了 comp() 成员函式可以比较 MyObj 物件
的大小,现欲利用此 comp() 函式来排列 list 元素的顺序,如何呼叫
list::sort(...) 呢?
解法分两种情形,
一、若 comp() 是 static member function 的话,
就直接将函式指标丢给 sort(), 亦即
mylist.sort(&MyObj::comp);
这个 comp() 长这样:
class MyObje {
public:
//...
static bool comp(const MyObj& lhs, const MyObj& rhs)
{
return lhs.data < rhs.data;
}
//...
};
二、若 comp() 是 non-static member function 的话,
就利用 STL 的 <functional> 提供的 mem_fun_ref() adapter
来包装一下。再丢给 sort(), 亦即
mylist.sort(mem_fun_ref(&MyObj::comp));
此 comp() 的宣告及定义见以下。我之前写的做法竟然不知
利用 mem_fun_ref(),而另外弄了一个 global function 来
包裹 comp(), 殊无必要,徒然降低效能。
: // using function pointer for list.sort()
: #include <iostream>
: #include <list>
: #include <iterator>
#include <functional>
: 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;
//上面令人感到 Orz 的两行改成一行即可
return data < other.data;
: }
: friend ostream& operator<< (ostream& os, const MyObj& my);
: private:
: int data;
: };
: ostream& operator<< (ostream& os, const MyObj& my)
: {
: return os << my.data;
: }
: // 原先的复杂写法,简单改用 global function 来做
我原先复杂的写法,其实是重新发明了不高明的轮子。
这个 mem_comp() 就不要了。
/*
: 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); // 注意用法,不写 & 也行
// 改成
mylist.sort(mem_fun_ref(&MyObj::comp));
: }
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.130.208.168