使用 boost::lambda 调用成员函数

发布于 2024-08-15 06:48:27 字数 748 浏览 5 评论 0原文

我正在学习 boost::lambda 库,为此我编写了此示例代码以将 vector 转换为 vector通过从 A 对象中提取值。

class A
{
public:
    A(int n) : m_n(n){}
    int get() const {return m_n;}

private:
    int m_n;

};

int _tmain(int argc, _TCHAR* argv[])
{
    using namespace boost::lambda;

    std::vector<A> a1;
    std::vector<int> a2;
    a1.push_back(A(10));
    a1.push_back(A(20));

    std::for_each(a1.begin(), a1.end(), bind(&std::vector<int>::push_back, var(a2), bind(&A::get, _1)));

    return 0;
}

经过多次尝试,我可以让 for_each 部分正常工作。但我仍然不喜欢那些多重绑定。有没有其他方法可以写这个。最好我想做一些类似的事情:a2.push_back(bind(&A::get,_1));,但这不能编译。

I am learning the boost::lambda library and for that I wrote this sample code to convert an vector<A> into vector<int> by extracting the value from A object.

class A
{
public:
    A(int n) : m_n(n){}
    int get() const {return m_n;}

private:
    int m_n;

};

int _tmain(int argc, _TCHAR* argv[])
{
    using namespace boost::lambda;

    std::vector<A> a1;
    std::vector<int> a2;
    a1.push_back(A(10));
    a1.push_back(A(20));

    std::for_each(a1.begin(), a1.end(), bind(&std::vector<int>::push_back, var(a2), bind(&A::get, _1)));

    return 0;
}

I could get the for_each part to work after several tries. But I still don't look the like of it with those multiple binds. Is there any other way to write this. Preferably I would like to do something like: a2.push_back(bind(&A::get,_1));, but that doesn't compile.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风透绣罗衣 2024-08-22 06:48:27

我认为你想做的事情是不可能的。 for_each 将函数应用于范围中的每个元素,但您试图调用两个成员函数,并且必须将它们都绑定。我认为您的代码是使用 for_each 时可以做的最好的事情。 Lambda 文档对我来说看起来非常完整,但没有您想要执行的操作的示例。我认为这是有原因的,有一个更合适的算法。正如基里尔所说,这是变换

std::transform(a1.begin(), a1.end(), std::back_inserter(a2), bind(&A::get, _1));

I don't think what you're trying to do is possible. for_each applies function to each element in the range, but you are trying to call two member functions and you'll have to bind them both. I think your code is the best you can do when using for_each. Lambda documentation looks very complete to me, but there is no example for what you're trying to do. I think it's for a reason, there is a more appropriate algorithm for this. As Kirill said it's transform.

std::transform(a1.begin(), a1.end(), std::back_inserter(a2), bind(&A::get, _1));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文