2009-11-05 65 views

回答

4

使用的std :: mem_fun,你必須通過指針類作爲第一個參數。你可以在這種情況下將它綁定到std :: bind1st。

class A 
{ 
public: 
    void print(int v) {std::cout << v;} 

    void load() 
    { 
     std::vector<int> vt(10, 20); 

     std::for_each(vt.begin(), vt.end(), std::bind1st(std::mem_fun(&A::print), this)); 
    } 
} 
+0

問題是,mem_fun將其應用在一個實例,但VT包含'int's尖的由AraK提供。 – 2009-11-05 08:25:50

+0

@Matthieu:不,mem_fun將方法轉換爲二進制函子。 bind1st接受一個二元函子,並將其變成一個一元函子。在這種情況下,'mem_fun'參數是'A *'和'int';作爲第一個參數綁定'this'會留下一個一元函數,並且按照預期的那樣採用'int'。 – MSalters 2009-11-05 09:00:31

4

vt有什麼A類型的整數不是對象。此外,print沒有操縱任何成員變量的,只是讓static

class A{ 

void load() 
{ 
vector<int> vt(10,20); 
std::for_each(vt.begin(), vt.end(), A::print); // static functions are regular functions 
} 

static void print(int a) 
{ 
cout<<a; 
} 

}; 
3

我發現boost :: bind很有幫助。這樣我就不必記住所有與std :: mem_fun相關的規則。

#include <boost/bind.hpp> 
class A{ 

void load() 
{ 
    vector<int> vt(10,20); 
    std::for_each(vt.begin(), vt.end(), boost::bind(&A::print,this,_1)); 
} 

void print(int a) 
{ 
    cout<<a; 
} 
}; 

儘管在這種特殊情況下,我寧願副本ostream_iterator成語:

copy(vt.begin(), vt.end(), ostream_iterator<int>(cout, " "));