在语句中有一个函数for_each

Having a function inside for_each statement

本文关键字:for each 函数 有一个 语句      更新时间:2023-10-16

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

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

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

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

由于它是一个成员函数,因此您需要将其包装在对象上调用它的函子中;大概是调用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));

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

您需要使用结构,如下所示:

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)

addToTemporaryVector函数不使用this。因此,您可以将其声明为静态。

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

声明:

static void addToTemporaryVector(const SomeType & item);

然后只需做:

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