4

我正在使用内置函数qsort()class item指针向量进行排序。

class item {
int value;
vector<char> c;
...
...
};

//Declaration of vector
vector<item*> items;

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

int value_sort(const void* a, const void* b)
{
item* pa = *(item**) a;
item* pb = *(item**) b;

if (pb->value < pa->value)
    return 1;
else if (pa->value < pb->value)
    return -1;
return 0;
}

在调试器模式下,指针既不指向pa也不pb指向有效位置。class items所指向的所有数据成员的集合pa或者pb包含垃圾值。我在哪里犯错?我也不确定双指针的用法。

谢谢。

4

3 回答 3

6

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)

于 2011-02-07T19:48:42.233 回答
4

不要qsort在 C++ 中使用,std::sort而是使用:

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

std::sort(items.begin(), items.end(), value_sort);
于 2011-02-07T19:45:04.290 回答
3

使用 std::sort 从algorithm. 它易于使用,键入安全且比 qsort 更快,并且没有指针问题:)。

#include <algorithm>

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

std::sort(items.begin(),items.end(),comparisonFunction);
于 2011-02-07T19:41:46.497 回答