使用 lambda 函数对 stl 容器进行排序

sorting stl containers with lambda functions

我有一个用户定义的向量 class,我想对这个向量进行排序。将根据 3 个属性进行排序。我正在使用 lambda 函数来捕获应根据其对向量进行排序的属性。但是,我收到编译器错误。我正在粘贴以下代码:

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

}

我得到的错误如下:

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 是一个 struct。它的声明是:

typedef struct Photon {

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

} Photon;

Vector 是一个 class,其私有成员是:

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

std::sort() 的前两个参数应该是迭代器,而不是对容器内容的引用。指针也可以工作,所以:

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

由于您没有提供 Minimum, Complete, and Verifieable example,您的代码可能还有其他问题阻止了编译,但这至少是其中的第一个。