2014-12-04 48 views
0

我不断收到错误信息,同时试图通过一个for_each的循环中的功能。我有一个载体,我用的for_each循环都要经过排在载体,现在我需要的功能做一些拥有的for_each语句中的函数

例如,这就是我想实现:

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

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

但我得到一个错误消息说:错误:无效使用无效表达他们两人都是在同一类的。

+1

你需要传递一个函数,而不是结果打一个。但请注意,传递成员函数是棘手的,因为它需要一个对象来执行。 – juanchopanza 2014-12-04 13:13:27

+0

所以你的意思是,我应该创建一个结构并在其中包含函数? – George 2014-12-04 13:15:58

+0

@George你应该做的是这样的:http://stackoverflow.com/questions/5050494/member-function-pointer-in-c-for-each – nos 2014-12-04 13:17:47

回答

0

因为它是一个成员函数,你需要把它包在调用它的对象上的仿函数;想必同一对象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)); 

我不能完全肯定这是否会与像不带参数你的函数工作;但大概你的真实代码确实需要一个参数来对每个元素进行一些操作。

0

您需要使用结构如下:

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; 
} 

需要注意的是操作者的输入必须是相同的载体类型。 (串在此实例中,整数中的链接)

0

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

此外,应采取作为参数label

宣言的模板类型:

static void addToTemporaryVector(const SomeType & item); 

然后,只需做:

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