2017-06-29 28 views
0

我一直在嘗試使用STL算法來處理多維數組的元素,似乎沒有任何東西與它們綁定。我該怎麼做:如何將STL算法的lambdas綁定到C風格的多維數組?

// Declaration of pix: 
float pix[1000][2]; 

// (...) 

const int sizeToParse = 300; 
static auto colLessThan = [] 
    (const float coordPair_lhs[2], const float coordPair_rhs[2]) -> bool 
    // (const float** coordPair_lhs, const float** coordPair_rhs) -> bool 
    // (const float* coordPair_lhs[], const float* coordPair_rhs[]) -> bool 
{ 
    return coordPair_lhs[1] < coordPair_rhs[1]; 
}; 
float** lhsColMinIt; 
float** lhsColMaxIt; 
// float* lhsColMinIt[2]; 
// float* lhsColMaxIt[2]; 
std::tie(lhsColMinIt, lhsColMaxIt) = std::minmax_element(pix, pix + sizeToParse, colLessThan); 

我所有的嘗試都被一個編譯器錯誤拒絕。

接受的答案後,它被認爲是減少到這一點:

In instantiation of ‘std::tuple<_T1, _T2>& std::tuple<_T1, _T2>::operator=(std::pair<_U1, _U2>&&) [with _U1 = const float ()[2]; _U2 = const float ()[2]; _T1 = float (&)[2]; _T2 = float (&)[2]]’:src/ClusterPairFunctions.cc:32:109: required from here /data/hunyadi/usr/include/c++/7.1.0/tuple:1252:25: error: invalid conversion from ‘const float () [2]’ to ‘float ()[2]’ [-fpermissive]

更新: 使用公認的答案提供的方法,代碼工作,我只是沒能還原函數,該編譯器報告常量不正確std::tuple

+0

能否請您詳細說明你有你展示的代碼的問題?它不是建立?你有沒有崩潰?意外的結果?還有別的嗎? –

+0

另外,請發佈[MVCE](https://stackoverflow.com/help/mcve)以提供重現問題的機會。 – skypjack

+0

不知道更多(因爲你沒有*顯示*我們的編譯器錯誤)我想這與類型不匹配有關。 lambda的參數是指向float的指針(即float *),但是數組「pix」的元素是兩個float類型的數組*,即類型float [2]。該解決方案顯示在[Jarod42的答案](https://stackoverflow.com/a/44824958/440558)中。 –

回答

2

在C++ 14中,在lambda中使用const auto&

如果你必須明確地提供類型:

static auto colLessThan = [] (const float (&lhs)[2], const float (&rhs)[2]) 
{ 
    return lhs[1] < rhs[1]; 
}; 

float (*lhsColMinIt)[2]; 
float (*lhsColMaxIt)[2]; 
std::tie(lhsColMinIt, lhsColMaxIt) = 
    std::minmax_element(pix, pix + sizeToParse, colLessThan); 

Demo

+3

也許你可以詳細闡述一下你所做的改變,以及爲什麼你創造了它們? –

+0

我確認這確實有效,我的代碼仍然拒絕用它編譯:( –