我有以下代码来对自定义类型的矢量进行排序。它曾经工作,但在另一个系统上构建代码后,它在编译时出错。
调用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))
^
^
正如我所说,这是在另一个系统上构建代码之后发生的。我认为它与改变编译器版本有关,但是我认为像sort函数一样简单的东西不会破坏。另外,如果是这种情况,我希望在两个编译器上编译代码。
真的很感激一些帮助,
答案 0 :(得分:4)
您的代码正在尝试对const对象进行非const引用,这是不允许的。比较函数不会修改其参数,因此更改:
<input name="ctl00$uniqueBody$ctl86" type="text" value="EXAMPLE" runat="server">
要
bool AssemblyObject::compare(AssemblyObject &a, AssemblyObject &b){
答案 1 :(得分:3)
错误很明显 - 您需要compare
接受const
左值参考,而不是可变的:
bool AssemblyObject::compare(const AssemblyObject &a, const AssemblyObject &b)
{
/* as before */
}