Search code examples
c++multidimensional-arraylambdastl-algorithm

How to bind lambdas for STL algorithms to C style multidimensional arrays?


I've been trying to use the STL algorithms to work with elements of multidimensional arrays, and nothing seems to bind to them. How do I do this:

// 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);

All of my attempts are rejected with a compiler error.

After the accepted answer it got reduced to this:

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]

Update: Using the method provided by the accepted answer, the code works, I just failed to demangle that the compiler was reporting const incorrectness inside std::tuple.


Solution

  • In C++14, use const auto& in the lambda.

    If you have to provide type explicitly:

    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