Reputation: 6926
There are plenty of examples on how to use std::sort()
with a std::vector
. For my specific homework assignment, I'm not allowed to use an std::vector
, so I instead want to use std::sort()
on a dynamic array of custom objects.
Like so:
int numberOfRoads = 100000;
Road* roads = new Road[numberOfRoads];
// Assume the comparator is defined correctly (<- this was the problem)
std::sort(roads, roads + numberOfRoads, SortRoadsComparator);
And here is the main compiler error I receive:
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
I receive this error about 20 times. What exactly is it requiring me to do?
SortRoadsComparator()
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
}
}
}
Solved by billz's comment.
Upvotes: 2
Views: 2475
Reputation: 45440
SortRoadsComparator
function prototype should be:
bool SortRoadsComparator(Road const& v1, Road const& v2);
You should make sure SortRoadsComparator
returns weak ordered Road
.
Upvotes: 2
Reputation: 44268
It requires you to pass proper comparator into std::sort. If you read std::sort documentation you can see that it requires following signature:
bool cmp(const Type1 &a, const Type2 &b);
and:
The types Type1 and Type2 must be such that an object of type RandomIt can be dereferenced and then implicitly converted to both of them.
So in your case dereferenced "iterator" roads has type Road& and function could be something like:
bool cmp( const Road &a, const Road &b );
PS Looks like you are porting qsort code into C++. Though suggestion to make signature to:
int cmp( const Road &a, const Road &b );
will compile, it is logically incorrect and would hide the fact that you need to change returned values in your function and slightly change the logic. In current implementation std::sort will most probably crash, but definatelly will not sort your sequence the way you expect it to.
Upvotes: 3