【问题标题】:Having a function inside for_each statement在 for_each 语句中有一个函数
【发布时间】:2014-12-04 13:12:32
【问题描述】:

我在尝试在 for_each 循环中传递函数时不断收到错误消息。我有一个向量,我使用 for_each 循环遍历该向量中的行,现在我需要一个函数来做某事

这就是我想要实现的示例:

void DataPartitioning::doSomething()
{
    for_each (label.begin(), label.end(), addToTemporaryVector());
}

void DataPartitioning::addToTemporaryVector()
{
    cout<<"sucess";
}

但我收到一条错误消息:错误:无效使用无效表达式,它们都在同一个类中。

【问题讨论】:

  • 你需要传递一个函数,而不是调用一个函数的结果。但请注意,传递一个成员函数很棘手,因为它需要一个对象来操作。
  • 你的意思是,我应该创建一个结构并在其中包含函数?
  • @George 你应该这样做:stackoverflow.com/questions/5050494/…
  • @George:或者使用 lambda,或std::bind,或常规 for 循环。
  • 如果你的编译器支持,check out the range-based for loop.

标签: c++


【解决方案1】:

因为它是一个成员函数,你需要将它包装在一个函子中,在一个对象上调用它;大概是调用 doSomething 的同一对象:

for_each(label.begin(), label.end(), [this](whatever const &){addToTemporaryVector();});

其中whatever 是容器的值类型。

作为常规的for循环可能会更清晰:

for (whatever const & thing : label) {
    addToTemporaryVector();
}

这假设您没有使用 C++11 之前的编译器。如果你是,它需要更多的胡言乱语:

for_each(label.begin(), label.end(),
    std::bind1st(std::mem_fun(&DataPartitioning::addToTemporaryVector), this));

我不完全确定这是否适用于像你这样不带参数的函数;但大概你的真实代码确实需要一个参数来对每个元素做一些事情。

【讨论】:

    【解决方案2】:

    你需要在这里使用一个结构体:

    http://en.cppreference.com/w/cpp/algorithm/for_each

    #include <iostream>
    #include<string>
    
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    struct Operation
    {
        void operator()(string n) { cout<<"success"<<endl; }
    };
    
    int main() {
        vector<string> vInts(10,"abc");
      std::for_each(std::begin(vInts), std::end(vInts), Operation());   
        // your code goes here
        return 0;
    }
    

    请注意,运算符的输入必须与向量中的类型相同。 (本例中为字符串,链接中为int)

    【讨论】:

      【解决方案3】:

      addToTemporaryVector 函数不使用this。所以你可以将它声明为静态的。

      另外,它应该将label的模板类型作为参数

      声明:

      static void addToTemporaryVector(const SomeType & item);
      

      那就这样吧:

      //No parentheses to the function pointer
      for_each (label.begin(), label.end(), addToTemporaryVector);
      

      【讨论】:

        猜你喜欢
        • 2021-06-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-18
        • 2010-09-07
        • 1970-01-01
        • 2019-03-19
        相关资源
        最近更新 更多