Using qsort() with class pointers

青春壹個敷衍的年華 提交于 2019-12-05 18:07:12

I agree with the answers that advise using std::sort. But ignoring that for the moment, I think the reason for your problem is that you're passing the address of the vector object, not the contents of the vector. Try this:

//Function Call
qsort(&items[0], items.size(), sizeof(item*), value_sort);

Then after you try that, go back and use std::sort instead. 8v)

Don't use qsort in C++, use std::sort instead:

int value_sort(item* pa, item* pb)
{
    return pa->value < pb->value;
}

std::sort(items.begin(), items.end(), value_sort);

Use std::sort from algorithm. It is easy to use, type safe and faster than qsort and haven't problems with pointers :).

#include <algorithm>

inline bool comparisonFuncion( item *  lhs,item  * rhs)
{
    return lhs->value<rhs->value;
}

std::sort(items.begin(),items.end(),comparisonFunction);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!