3 回答

TA貢獻1804條經驗 獲得超2個贊
doCompare必須是static。如果doCompare需要來自MyClass您的數據,可以MyClass通過更改以下內容將其用作比較函子:
doCompare( const int & i1, const int & i2 ) { // use some member variables }
進入
bool operator () ( const int & i1, const int & i2 ) { // use some member variables }
并致電:
doSort() { std::sort(arr,arr+someSize, *this); }
另外,不doSort缺少返回值嗎?
我認為應該可以使用std::mem_fun某種綁定將成員函數轉換為自由函數,但是目前確切的語法讓我回避了。
編輯: Doh,std::sort按值取函子可能是個問題。為了解決這個問題,將函子包裝到類中:
class MyClass {
struct Less {
Less(const MyClass& c) : myClass(c) {}
bool operator () ( const int & i1, const int & i2 ) {// use 'myClass'}
MyClass& myClass;
};
doSort() { std::sort(arr,arr+someSize, Less(*this)); }
}

TA貢獻1875條經驗 獲得超5個贊
正如Andreas Brinck所說,doCompare必須為靜態(+1)。如果您必須在比較器函數中使用狀態(使用該類的其他成員),則最好使用函子而不是函數(這樣會更快):
class MyClass{
// ...
struct doCompare
{
doCompare( const MyClass& info ) : m_info(info) { } // only if you really need the object state
const MyClass& m_info;
bool operator()( const int & i1, const int & i2 )
{
// comparison code using m_info
}
};
doSort()
{ std::sort( arr, arr+someSize, doCompare(*this) ); }
};
使用函子總是更好,鍵入的時間更長(這可能不方便,但是很好...)
我認為您也可以將std :: bind與成員函數一起使用,但是我不確定如何并且那也不容易閱讀。
今天,我們可以使用c ++ 11編譯器,因此您可以改用lambda,代碼雖然較短,但語義完全相同。

TA貢獻1828條經驗 獲得超3個贊
Rob提出的解決方案現在是有效的C ++ 11(無需Boost):
void doSort()
{
using namespace std::placeholders;
std::sort(arr, arr+someSize, std::bind(&MyClass::doCompare, this, _1, _2));
}
確實,正如Klaim所提到的,lambda是一個選項,有點冗長(您必須“重復”這些參數是整數):
void doSort()
{
std::sort(arr, arr+someSize, [this](int l, int r) {return doCompare(l, r); });
}
C ++ 14 auto在這里支持:
void doSort()
{
std::sort(arr, arr+someSize, [this](auto l, auto r) {return doCompare(l, r); });
}
但是,您仍然聲明參數是通過副本傳遞的。
那么問題是“哪一個是最有效的”。特拉維斯·高克爾(Travis Gockel)處理了該問題:Lambda vs Bind。他的基準測試程序在我的計算機上提供(OS X i7)
Clang 3.5 GCC 4.9
lambda 1001 7000
bind 3716166405 2530142000
bound lambda 2438421993 1700834000
boost bind 2925777511 2529615000
boost bound lambda 2420710412 1683458000
其中lambda的lambda直接使用,lambda bound是存儲在中的lambda std::function。
因此看來,lambda是更好的選擇,這并不奇怪,因為為編譯器提供了可從中獲利的更高級別的信息
- 3 回答
- 0 關注
- 374 瀏覽
添加回答
舉報