2010-08-18 47 views
1
#include <iostream> 
#include <set> 
#include <algorithm> 
#include <boost/lambda/lambda.hpp> 
#include <boost/bind.hpp> 

using namespace std; 
using namespace boost::lambda; 



class Foo { 
public: 
    Foo(int i, const string &s) : m_i(i) , m_s(s) {} 
    int get_i() const { return m_i; } 
    const string &get_s() const { return m_s; } 
    friend ostream & operator << (ostream &os, const Foo &f) { 
     os << f.get_i() << " " << f.get_s().c_str() << endl; 
     return os; 
    } 
private: 
    int m_i; 
    string m_s; 
}; 

typedef set<Foo> fooset; 
typedef set<int> intset; 


int main() 
{ 
    fooset fs; 
    intset is; 

    fs.insert(Foo(1, "one")); 
    fs.insert(Foo(2, "two")); 
    fs.insert(Foo(3, "three")); 
    fs.insert(Foo(4, "four")); 

    transform(fs.begin(), fs.end(), inserter(is, is.begin()), boost::bind(&Foo::get_i, _1)); 

    std::for_each(fs.begin(), fs.end(), cout << _1 << endl); 
    std::for_each(is.begin(), is.end(), cout << _1 << endl); 

    return 0; 
} 

這是我的代碼示例。我想要for_each一組Foo併產生一組Foo類型的成員,在本例中爲int。我不確定我做錯了什麼,但我確實做錯了什麼。提升lambda問題

TIA for your help!

編輯:感謝夥計們!工作代碼是...

#include <iostream> 
#include <set> 
#include <algorithm> 
#include <boost/lambda/lambda.hpp> 
#include <boost/lambda/bind.hpp> 
#include <boost/bind.hpp> 

using namespace std; 
using namespace boost::lambda; 


class Foo { 
public: 
    Foo(int i, const string &s) : m_i(i) , m_s(s) {} 
    int get_i() const { return m_i; } 
    const string &get_s() const { return m_s; } 
    friend ostream & operator << (ostream &os, const Foo &f) { 
     os << f.get_i() << " " << f.get_s().c_str() << '\n'; 
     return os; 
    } 

private: 
    int m_i; 
    string m_s; 
}; 

bool operator < (const Foo &lf, const Foo &rf) { 
    return (lf.get_i() < rf.get_i()); 
} 

typedef set<Foo> fooset; 
typedef set<int> intset; 


int main() 
{ 
    fooset fs; 
    intset is; 

    fs.insert(Foo(1, "one")); 
    fs.insert(Foo(2, "two")); 
    fs.insert(Foo(3, "three")); 
    fs.insert(Foo(4, "four")); 

    transform(fs.begin(), fs.end(), inserter(is, is.begin()), boost::lambda::bind(&Foo::get_i, boost::lambda::_1)); 

    std::for_each(fs.begin(), fs.end(), cout << boost::lambda::_1 << '\n'); 
    std::for_each(is.begin(), is.end(), cout << boost::lambda::_1 << '\n'); 

    return 0; 
} 
+0

您的代碼不能編譯。這是你想要幫助的問題嗎? – zwol 2010-08-18 19:39:13

回答

2

這個程序運行,併產生預期的輸出如下修改後:

  1. 實現Foo::operator<(const Foo&) const(否則set<Foo>不會編譯)
  2. typedef set<Foo> fooset;後boost.bind之間class Foo
  3. 歧義_1 boost.lambda佔位符
  4. 使用'\ n'而不是endl,如前所述。
1

首先不要混淆boost :: bind和boost :: lambda :: bind,它們是不同的東西。

更改調用的boost ::綁定的foreach循環來此(刪除了boost ::前綴):

bind (&Foo::get_i, _1) 

然後在底部更改endl s到'\n'