提升lambda问题

时间:2010-08-18 19:28:50

标签: c++ boost lambda stl-algorithm

#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。我不太确定我做错了什么,但我肯定做错了。

TIA求助!

编辑:感谢伙计们!工作代码如下......

#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;
}

2 个答案:

答案 0 :(得分:2)

此程序在以下更改后运行并生成预期输出:

  1. 实施Foo::operator<(const Foo&) const(否则set<Foo>将无法编译)
  2. typedef set<Foo> fooset;
  3. 之后添加class Foo
  4. 在boost.bind和boost.lambda占位符之间消除_1的歧义
  5. 使用'\ n'而不是endl,如前所述。

答案 1 :(得分:1)

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

将foreach循环中对boost :: bind的调用更改为this(删除boost ::前缀):

bind (&Foo::get_i, _1)

然后将底部的endl更改为'\n'