使用排序时类型初始化无效

Invalid initialization of type when using sort

我有以下代码来对自定义类型的向量进行排序。它曾经有效,但在另一个系统上构建代码后,它在编译时出错。

进行 sort() 调用的上下文。

std::vector<std::vector<AssemblyObject>>*     LegoAssembler::getLayers(std::vector<AssemblyObject> completeAssembly)
{    
    std::vector<std::vector<AssemblyObject>>* layers = new std::vector<std::vector<AssemblyObject>>();
    std::vector<AssemblyObject> cLayer;

    double lastZ = 0;
    std::sort(completeAssembly.begin(), completeAssembly.end(), AssemblyObject::compare);

    ...
}

排序函数

bool AssemblyObject::compare(AssemblyObject &a, AssemblyObject &b){
return (a.getPosition()[2] < b.getPosition()[2]) ||
       ((a.getPosition()[2] == b.getPosition()[2]) && (a.getPosition()[1] > b.getPosition()[1])) ||
       ((a.getPosition()[2] == b.getPosition()[2]) && (a.getPosition()[1] == b.getPosition()[1]) && (a.getPosition()[0] > b.getPosition()[0]));
}

错误

/usr/include/c++/4.8/bits/stl_algo.h:2263: error: invalid initialization of reference of type ‘AssemblyObject&’ from expression of type ‘const AssemblyObject’
while (__comp(*__first, __pivot))

/usr/include/c++/4.8/bits/stl_algo.h:2263: error: invalid initialization of reference of type ‘AssemblyObject&’ from expression of type ‘const AssemblyObject’
while (__comp(*__first, __pivot))
                               ^
                               ^

正如我所说,这是在另一个系统上构建代码之后发生的。我认为它与更改编译器版本有关,但话又说回来,我认为像排序函数这样简单的东西不会中断。另外,如果是这样的话,我希望代码可以在两个编译器上编译。

非常感谢您的帮助,

错误很明显 - 你需要 compare 来接受 const lvalue-references,而不是可变的:

bool AssemblyObject::compare(const AssemblyObject &a, const AssemblyObject &b)
{ 
    /* as before */
}

您的代码试图获取对 const 对象的 non-const 引用,这是不允许的。比较函数不修改其参数,因此更改:

bool AssemblyObject::compare(AssemblyObject &a, AssemblyObject &b){

bool AssemblyObject::compare(const AssemblyObject &a, const AssemblyObject &b){