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

これが私のコード例です。Foo のセットを for_each して、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;
}
4

2 に答える 2

2

このプログラムが実行され、次の変更後に期待される出力が生成されます。

  1. 実装しますFoo::operator<(const Foo&) const(そうset<Foo>しないとコンパイルされません)
  2. typedef set<Foo> fooset;後に置くclass Foo
  3. boost.bind と boost.lambda プレースホルダーの間の _1 を明確にする
  4. すでに述べたように、endl の代わりに '\n' を使用してください。
于 2010-08-18T19:39:51.377 に答える
1

まず、boost::bind と boost::lambda::bind を混同しないでください。これらは別のものです。

foreach ループ内の boost::bind への呼び出しを次のように変更します (boost:: プレフィックスを削除します)。

bind (&Foo::get_i, _1)

次にendl、下部の s を に変更し'\n'ます。

于 2010-08-18T19:36:14.283 に答える