C ++对象的快速排序向量 [英] c++ quicksort vector of objects
问题描述
在我的对象向量上使用std :: qsort时遇到麻烦.(请注意,此代码在循环内)
I am having troubles using std::qsort on my vector of objects. (Note that this code is inside a loop)
std::vector<s_GridData> info = GetAllAdjacentObjInfoFromMap(FLOOR_OBJ, e_Object::eObject_WIRE, itr.getPos());
//No wires adjacent!
if (info.size() == 0) {
continue;
}
std::cout << "Before sorting: ";
std::cout << info;
std::qsort(&info, info.size(), sizeof(s_GridData),
[](const void *lhs, const void *rhs)->int {
s_GridData gridLhs = *reinterpret_cast<const s_GridData*>(lhs);
s_GridData gridRhs = *reinterpret_cast<const s_GridData*>(rhs);
if (gridLhs.groupID < gridRhs.groupID) return -1;
if (gridRhs.groupID < gridLhs.groupID) return 1;
return 0;
}
);
std::cout << "After sorting: ";
std::cout << info;
在快速排序代码中,似乎该快速排序正在擦除我的 info
.Lambda出问题了吗?还是有另一个使用qsort的要求,例如赋值运算符重载.但是 s_GridData
仅仅是整数值的结构.
Here specifically in the quicksort code, it seems that the quicksort is erasing my info
.
Is there something wrong with the lambda? Or is there another requirement for using qsort like an assignment operator overload. However s_GridData
is simply a struct of integral values.
谢谢.
推荐答案
您正在将错误的参数传递给 qsort()
(这实际上是C函数,最初不在 namespace std中
):
You're passing the wrong arguments to qsort()
(which is really a C function not originally in namespace std
):
std::qsort(&info, ...
马上就错了,因为 info
是 std :: vector
,但是 qsort()
需要C样式的数组.您可以通过以下方式解决它:
Right off the bat that's wrong, because info
is a std::vector
but qsort()
requires a C-style array. You can fix it this way:
std::qsort(info.data(), ...
或在C ++ 11之前:
Or before C++11:
std::qsort(&info[0], ...
但是,更好的解决方案是使用 std :: sort()
,这是一种真正的 C ++函数,具有类型安全性和其他优点.它是这样的:
However, the better solution is to use std::sort()
, which is a bona fide C++ function giving type safety and other benefits. It goes something like this:
sort(info.begin(), info.end(),
[](const s_GridData& lhs, const s_GridData& rhs)->bool {
return gridLhs.groupID < gridRhs.groupID;
});
如您所见,C ++方式更为简洁,并且如果您的排序适用于所有实例,则可以单独定义(通常是内联自由函数),在这种情况下:
As you can see, the C++ way is more concise, and if your ordering is applicable across all your instances, you can define it separately (typically as an inline free function), in which case:
sort(info.begin(), info.end());
这篇关于C ++对象的快速排序向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!