Search code examples
c++algorithmlambdakdtree

sorting stl containers with lambda functions


I have a vector of a user defined class and I want to sort this vector. There will be 3 attributes based on which the sorting can happen. I am using lambda function to capture the attribute based on which the vector should be sorted. However, I am getting compiler errors. I am pasting the code below:

mapNode * PhotonMap::createTree(int start, int end)
{
    mapNode *n = new mapNode();

    if (end - start == 0)
    {
        n->node.sPosition.setVector(pMap[end].sPosition);
        n->node.pPower.setVector(pMap[end].pPower);
        n->sAxis = -1;
        n->left = NULL;
        n->right = NULL;
        return n;
    }

    BBox box;

    if (!(end - start + 1 == pMap.size()))
        box.setBBox(computeBox(start, end));

    int splitAxis = decodeSplitAxis(box.getMaxSpreadAxis());
    n->sAxis = splitAxis;

    std::sort(pMap[start], pMap[end], [splitAxis](Photon &first, Photon &second) ->bool { return (first.sPosition.getValue(splitAxis) > second.sPosition.getValue(splitAxis)); });

    int mIndex = floor((start + end) / 2);

    n->node.sPosition.setVector(pMap[mIndex].sPosition);
    n->node.pPower.setVector(pMap[mIndex].pPower);

    if (mIndex == start)
    {
        //this means end - start = 1. There will be no left node!
        n->left = NULL;
        n->right = createTree(mIndex + 1, end);
        return n;
    }
    else {
        n->left = createTree(start, mIndex);
        n->right = createTree(mIndex + 1, end);
        return n;
    }

}

The errors I am getting are the following:

error C2784: 'unknown-type std::operator -(std::move_iterator<_RanIt> &,const std::move_iterator<_RanIt2> &)': could not deduce template argument for 'std::move_iterator<_RanIt> &' from 'Photon'

error C2784: 'unknown-type std::operator -(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)': could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'Photon'

error C2676: binary '-': 'Photon' does not define this operator or a conversion to a type acceptable to the predefined operator

error C2672: '_Sort': no matching overloaded function found

error C2780: 'void std::_Sort(_RanIt,_RanIt,_Diff,_Pr)': expects 4 arguments - 3 provided

Photon is a struct. Its declaration is:

typedef struct Photon {

    Vector sPosition;
    Vector iDirection;
    Vector pPower;
    Vector norm;

} Photon;

Vector is a class whose private members are:

int length;
void allocateMemory(void);
float vector[3];

Solution

  • The first two parameters to std::sort() should be iterators, not references to the contents of the container. Pointers will work too, so:

    std::sort(&pMap[start], &pMap[end], /* your lambda goes here */);
    

    Since you did not provide a Minimum, Complete, and Verifieable example, there may also be other problems with your code that prevent compilation, but this is at least the first one of them.