Reputation: 1
I got a little problem with qSort. I just want to sort my list after adding a vertex to my QList m_acceptedVertices.
bool Vertex::greaterThan(Vertex * v1, Vertex *v2){
return this->computeDistanceTo(v1) > this->computeDistanceTo(v2);
}
void Vertex::acceptVertex(Vertex* vert)
{
m_acceptedVertices.append(vert);
qSort(m_acceptedVertices.begin(), m_acceptedVertices.end(), greaterThan);
}
But I still getting these Errors:
Fehler: C3867: 'Vertex::greaterThan': function call missing argument list; use '&Vertex::greaterThan' to create a pointer to member
Fehler: C2780: 'void qSort(Container &)' : expects 1 arguments - 3 provided
Fehler: C2780: 'void qSort(RandomAccessIterator,RandomAccessIterator)' : expects 2 > arguments - 3 provided
What am I doing wrong? Can sombody help me? Thanks!
Upvotes: 0
Views: 445
Reputation: 37607
If you are using C++11 then probably you need something like that:
void Vertex::acceptVertex(Vertex* vert)
{
m_acceptedVertices.append(vert);
qSort(hallo.begin(), hallo.end(),
[this](Vertex* v1, Vertex* v2) {
return this->computeDistanceTo(v1) > this->computeDistanceTo(v2);
});
}
If you use older C++ you have to define functor object which will store pointer reference Vertex, or use lambda expression from boost.
Upvotes: 2
Reputation: 23793
1) You have a design issue, your comparator is supposed to be a free function (or a functor) comparing 2 Vertex
, your implementation should probably look something like :
bool greaterThan(Vertex * v1, Vertex *v2){
return v1.computeDistanceTo(v2) > 0;
}
2) Use the standard library : std::sort
(it is most likely to perform a quicksort internally in most cases, but if you really want to use qSort
, it will work as well)
Minimal working example with a free function comparator :
class Vertex {
public:
int i;
};
bool greaterThan(Vertex * v1, Vertex *v2)
{
return v1->i > v2->i;
}
int main()
{
std::vector<Vertex*> v;
v.push_back(new Vertex { 5 });
v.push_back(new Vertex { 1 });
v.push_back(new Vertex { 3 });
v.push_back(new Vertex { 6 });
v.push_back(new Vertex { 2 });
std::sort(v.begin(), v.end(), &greaterThan);
for(auto& ve : v)
std::cout << ve->i << " ";
}
Note:
For simple comparison functions, lambdas are a good alternative:
std::sort(v.begin(), v.end(), [] (Vertex * v1, Vertex *v2) {return v1->i > v2->i;} );
Upvotes: 2