首先,你需要確保,當你使用它的比較級是可以確定的:在前面定義的移動MyComparator
定義countNames()
將是我的第一步。也就是說,bind2nd()
想知道它所處理的函數對象比你提供的要好一些:它通常想知道result_type
,first_argument_type
和second_argument_type
。你可以從std::binary_function<bool, CFileType const*, std::string const&>
或明確定義它們。雖然我不認爲這是必需的,但您可能需要使函數調用運算符const
。另一方面,如果你正在定義一個函數對象而不是一個函數(你可以使用std::ptr_fun()
來獲得必要的typedef
;個人而言,我認爲這個名字的意思是讓這些人有吸引力,因爲它肯定不是很多有趣當你不得不使用它們),你可以去整個的方式,而不是用在首位粘合劑爭戰
class MyComparator {
public:
MyComparator(std::string const& value): value_(value) {}
bool operator()(CFileType const* obj) const {
return obj->getName() == this->value_;
}
private:
std::string value_;
};
...
std::count_if(files.begin(), files.end(), MyComparator(name));
您可以定義一個函數,並結合其在使用粘合劑得到大致相同的效果。 Typeically,我做錯了,當我不嘗試一下代碼,但它會是這個樣子:
bool myComparator(CFileType const* obj, std::string name) {
return obj->getName() == name;
}
...
std::count_if(files.begin(), files.end(),
std::bind2nd(std::ptr_fun(myComparator), name));
如果你覺得你想通過引用傳遞的參數name
而不是複製這一切的時候,您將無法使用std::bind2nd()
,至少除非您使用C++ 2011編譯器:否則它將創建一個類型,該類型必須連續編譯器不會喜歡的const
關鍵字。您可以使用例如boost::bind()
不存在這個問題:
std::count_if(files.begin(), files.end(), boost::bind(myComparator, _1, name));
...並改變name
參數的聲明是std::string const& name
。
非常感謝,它工作完美,它比使用** bold ** bind2nd()**更加緊湊** bold ** – Goshutu 2012-03-06 10:35:04
@Goshutu我忘記了通過引用傳遞向量(請參閱編輯) 。這不會影響正確性,但會影響性能,因爲每次調用「CountMatchingNames」時不再需要複製向量。 – 2012-03-06 10:59:40
沒有問題,因爲這是一個類的成員函數 – Goshutu 2012-03-06 17:46:14