有很多关于如何std::sort()
使用std::vector
. 对于我的特定家庭作业,我不允许使用std::vector
,因此我想std::sort()
在自定义对象的动态数组上使用。
像这样:
int numberOfRoads = 100000;
Road* roads = new Road[numberOfRoads];
// Assume the comparator is defined correctly (<- this was the problem)
std::sort(roads, roads + numberOfRoads, SortRoadsComparator);
这是我收到的主要编译器错误:
C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\algorithm(3781): error C2664: 'int (const void *,const void *)' : cannot convert parameter 1 from 'Road' to 'const void *'
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
我收到此错误大约 20 次。它究竟需要我做什么?
排序道路比较器()
int SortRoadsComparator(void const *v1, void const *v2)
{
Road *a = (Road *)v1;
Road *b = (Road *)v2;
if (a->Length > b->Length)
return 1;
else if (b->Length > a->Length)
return -1;
else
{
// Non-determinism case
if (a->Length == b->Length)
{
if ( (min(a->CityA, a->CityB) < min(b->CityA, b->CityB)) ||
(
(min(a->CityA, a->CityB) == min(b->CityA, b->CityB)) && max(a->CityA, a->CityB) < max(b->CityA, b->CityB)
)
)
{
return -1;
}
else
{
return 1;
}
}
else
{
// Not expecting this
}
}
}
由 billz 的评论解决。