绑定的不是一个值,而是一个函数(获取该函数的值)

发布于 2025-01-01 12:45:55 字数 387 浏览 5 评论 0原文

假设我有以下功能:

int foo (int a)
{
  return something;
}

我怎样才能做这样的事情?

vector<int> v;

std::for_each( v.begin(), v.end(), std::bind1st(std::minus<int>(), foo) );

我希望它的工作方式如下: for_each 将当前元素传递到函子中,函子调用 foo 然后减去传递的向量元素和调用 foo 的结果>。是否可以仅使用 std 而不是 boost 或自己编写的函子来实现此目的?

Let's say I have following function:

int foo (int a)
{
  return something;
}

How can I do something like this?

vector<int> v;

std::for_each( v.begin(), v.end(), std::bind1st(std::minus<int>(), foo) );

I want this to work like: for_each passes current element into the functor, functor calls foo and then subtracts the passed vector element and result of calling foo. Is it possible to make this using only std, not boost or self-written functors?

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

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

发布评论

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

评论(2

说不完的你爱 2025-01-08 12:45:55

嗯,这有点可怕,但在 C++11 中……

#include <vector>
#include <functional>
#include <algorithm>

int foo(int a) 
{
    return a;
}

int operator-(int b, std::function<int(int)> a)
{
    return b - a(b);
}

int main()
{
    std::vector<int> v = {1,2,3,4,5};
    std::for_each( v.begin(), v.end(), std::bind((int(*)(int, std::function<int(int)>))(&operator-), std::placeholders::_1, &foo) );
    return 0;
}

使用 lambda 的方式不那么可怕

std::for_each(v.begin(), v.end(), [](int a) -> int { return a - foo(a); });

Well this is slightly horrible but in C++11...

#include <vector>
#include <functional>
#include <algorithm>

int foo(int a) 
{
    return a;
}

int operator-(int b, std::function<int(int)> a)
{
    return b - a(b);
}

int main()
{
    std::vector<int> v = {1,2,3,4,5};
    std::for_each( v.begin(), v.end(), std::bind((int(*)(int, std::function<int(int)>))(&operator-), std::placeholders::_1, &foo) );
    return 0;
}

less horrible way using lambdas

std::for_each(v.begin(), v.end(), [](int a) -> int { return a - foo(a); });
凡尘雨 2025-01-08 12:45:55

如果您不想修改该向量,那么我假设您想将其转换为另一个向量。

#include <algorithm>
#include <iterator>
#include <vector>

int foo(int a)
{
    return a;
}

int foo2(int a)
{
    return a - foo(a);
}

int main()
{
    std::vector<int> v;

    v.push_back(10);
    v.push_back(20);
    v.push_back(30);

    std::vector<int> v2;
    std::transform(v.begin(), v.end(), std::back_inserter(v2), foo2);

    return 0;
}

If you do not want to modify the vector, so I would assume you want to transform it to another one.

#include <algorithm>
#include <iterator>
#include <vector>

int foo(int a)
{
    return a;
}

int foo2(int a)
{
    return a - foo(a);
}

int main()
{
    std::vector<int> v;

    v.push_back(10);
    v.push_back(20);
    v.push_back(30);

    std::vector<int> v2;
    std::transform(v.begin(), v.end(), std::back_inserter(v2), foo2);

    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文