【问题标题】:sorting stl containers with lambda functions使用 lambda 函数对 stl 容器进行排序
【发布时间】:2016-03-19 02:04:22
【问题描述】:

我有一个用户定义类的向量,我想对这个向量进行排序。将有 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;
    }

}

我得到的错误如下:

错误 C2784:“未知类型 std::operator -(std::move_iterator<_ranit> &,const std::move_iterator<_ranit2> &)”:无法推断出“std::move_iterator<_ranit> &' 来自“光子”

错误 C2784:“未知类型 std::operator -(const std::reverse_iterator<_ranit> &,const std::reverse_iterator<_ranit2> &)”:无法推断出“const std::reverse_iterator”的模板参数<_ranit> &' 来自“光子”

错误 C2676:二进制“-”:“Photon”未定义此运算符或转换为预定义运算符可接受的类型

错误 C2672:“_Sort”:找不到匹配的重载函数

错误 C2780:'void std::_Sort(_RanIt,_RanIt,_Diff,_Pr)':需要 4 个参数 - 提供了 3 个

Photonstruct。它的声明是:

typedef struct Photon {

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

} Photon;

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

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

【问题讨论】:

    标签: c++ algorithm lambda kdtree


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 2012-11-30
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      相关资源
      最近更新 更多