简体   繁体   English

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

[英]Invalid initialization of type when using sort

I have the following code to sort a vector of a custom type. 我有以下代码对自定义类型的向量进行排序。 It used to work, but after building the code on another system it gives an error at compile time. 它曾经可以工作,但是在另一个系统上构建代码后,它在编译时给出了错误。

The context the sort() call is made. 进行了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);

    ...
}

The sorting function 排序功能

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

The Error 错误

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

As I said, this happened after building the code on another system. 如我所说,这是在另一个系统上构建代码之后发生的。 I was thinking it had something to do with changing compiler versions, but then again, I think something as simple as a sort function wouldn't break. 我当时以为它与更改编译器版本有关,但话又说回来,我认为像排序函数这样简单的事情不会中断。 Plus I'd like the code to compile on both compilers if that was the case. 另外,在这种情况下,我希望代码可以在两个编译器上进行编译。

Really would appreciate some help, 真的很感谢您的帮助,

Your code is attempting to take a non-const reference to a const object, which is not permitted. 您的代码正在尝试对const对象进行非const引用,这是不允许的。 The compare function doesnt modify its arguments so change: 比较函数不会修改其参数,因此请更改:

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

To

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

The error is pretty clear - you need compare to accept const lvalue-references , not mutable ones: 错误非常明显-您需要compare以接受const lvalue-references ,而不是可变的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM