将std :: function作为参数传递给for_each

时间:2015-12-10 17:21:50

标签: c++ algorithm vector foreach lambda

#include <initializer_list>
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>

std::function<void(int)> sample_function()
{
    return
        [](int x) -> void
    {
        if (x > 5)
            std::cout << x;
    };
}

int main()
{
    std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
    std::for_each(numbers.begin(), numbers.end(), sample_function);
}   

我正在尝试将sample_function()传递给for_each但我遇到此错误

错误C2197'std :: function':调用

的参数太多

2 个答案:

答案 0 :(得分:3)

我认为你想要的是以下

#include <iostream>
#include <vector>
#include <functional>

std::function<void(int)> sample_function =  [](int x)
{
    if (x > 5)  std::cout << x << ' ';
};


int main()
{
    std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
    std::for_each(numbers.begin(), numbers.end(), sample_function);
}

输出

10 15 20 25 35 45 50

或者,如果您确实要定义一个返回类型为std::function的对象的函数,那么您可以编写

#include <iostream>
#include <vector>
#include <functional>

std::function<void(int)> sample_function()
{
    return  [](int x)
            {
                if (x > 5)  std::cout << x << ' ';
            };
}


int main()
{
    std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
    std::for_each(numbers.begin(), numbers.end(), sample_function() );
}

输出与上面显示的相同。注意电话

    std::for_each(numbers.begin(), numbers.end(), sample_function() );
                                                                ^^^^

答案 1 :(得分:0)

您需要使用括号来唤起对sample_function的函数调用,而std::function会返回for_each的{​​{1}}对象:

std::function<void(int)> sample_function() {
  return [](int x) -> void {
     if (x > 5) std::cout << x;
  };
}

int main() {
    std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
    std::for_each(numbers.begin(), numbers.end(), sample_function());
                                                                 ^^
} 

Live Demo