2015-05-26 72 views
1

我有std::list<MyClass> *info1我想使用(*info1).remove_if與bool函數MyClass。正如我所看到的,每個人都爲remove_if創建外部函數或結構。難道不可以將它與bool MyClass::Condition()函數一起使用嗎?使用std :: list :: remove_if與MyClass的函數

像這樣:

class MyClass 
{ 
private: 
    int value; 
public: 
    bool Condition() 
    { 
     return (value > 7500); 
    } 
}; 

而且隨後

(*info1).remove_if(Condition())` 

回答

2

它通過std::mem_fn是可能的:

info1->remove_if(std::mem_fn(&MyClass::Condition)); 

Live demo

或通過std::bind

using namespace std::placeholders; 
info1->remove_if(std::bind(&MyClass::Condition, _1)); 

Live demo

兩者的那些功能都包含在標準<functional>報頭。

+1

「std :: mem_fn」的輸入較少。 –

+0

@ T.C。誠然,謝謝。 – Shoe

+0

謝謝,std :: mem_fn正如我所願。 – ergbil

-2

你想要做什麼是最好的用戶STD算法

std::remove_if(info1->begin(), info1->end(),[](MyClass x){return x.Condition();}) 
+0

Erm,['std :: list :: remove_if'](http://en.cppreference.com/w/cpp/container/list/remove)是一種標準算法。 – Shoe

+0

是的它是std :: remove_if的重新實現 –

+0

'std :: list :: remove_if'存在的原因。 –

-2

您可以使用MyClass中添加運算符(),並把它作爲這裏的謂詞是一個例子:

#include <iostream> 
#include <list> 

using namespace std; 
class MyClass 
{ 
    private: 
    int value; 
    public: 
    MyClass(int val) : value(val) {} 
    int get_value() const { return value; } 
    bool operator()(const MyClass& M) 
    { 
     return (M.value > 7500); 
    } 
}; 

int main() { 
    list<MyClass> v; 
    v.emplace_back(100); 
    v.emplace_back(10000); 
    v.emplace_back(500); 
    v.emplace_back(7500); 
    v.emplace_back(50000); 
    v.remove_if(MyClass(0)); 
    for (const auto& i : v) { 
    cout << i.get_value() << "\n"; 
    } 
    return 0; 
} 
+1

這是一個糟糕的主意,因爲你正在有效地使用'MyClass'作爲謂詞和別的東西(取決於'MyClass'的原始含義)。特別是如果'MyClass'不應該具有「可調用」語義。 – Shoe

+0

爲什麼我有-1這不工作?我真的測試過它。 – Brahim

相關問題