2014-12-04 54 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);