如何使用std ::排序与结构和比较函数的向量? [英] How to use std::sort with a vector of structures and compare function?
问题描述
感谢您使用C中的解决方案,
现在我想在C ++中使用std :: sort和vector实现:
Thanks for a solution in C, now I would like to achieve this in C++ using std::sort and vector:
typedef struct
{
double x;
double y;
double alfa;
} pkt;
pkt> wektor;
使用push_back()填充;比较函数:
vector< pkt > wektor;
filled up using push_back(); compare function:
int porownaj(const void *p_a, const void *p_b)
{
pkt *pkt_a = (pkt *) p_a;
pkt *pkt_b = (pkt *) p_b;
if (pkt_a->alfa > pkt_b->alfa) return 1;
if (pkt_a->alfa < pkt_b->alfa) return -1;
if (pkt_a->x > pkt_b->x) return 1;
if (pkt_a->x < pkt_b->x) return -1;
return 0;
}
sort(wektor.begin(), wektor.end(), porownaj); // this makes loads of errors on compile time
什么是正确的?在这种情况下如何正确使用std :: sort?
What is to correct? How to use properly std::sort in that case?
推荐答案
std :: sort
使用与 qsort
中使用的不同的比较函数。该函数不返回-1,0或1,而是返回一个 bool
值,表示第一个元素是否小于第二个元素。
std::sort
takes a different compare function from that used in qsort
. Instead of returning –1, 0 or 1, this function is expected to return a bool
value indicating whether the first element is less than the second.
你有两个可能性:为你的对象实现 operator<
在这种情况下,默认的 sort
调用没有第三个参数将工作;或者你可以重写你的上述函数来完成同样的事情。
You have two possibilites: implement operator <
for your objects; in that case, the default sort
invocation without a third argument will work; or you can rewrite your above function to accomplish the same thing.
注意你必须在参数中使用强类型。
Notice that you have to use strong typing in the arguments.
另外,不要在这里使用函数。而应使用函数对象。
Additionally, it's good not to use a function here at all. Instead, use a function object. These benefit from inlining.
struct pkt_less {
bool operator ()(pkt const& a, pkt const& b) const {
if (a.alfa < b.alfa) return true;
if (a.alfa > b.alfa) return false;
if (a.x < b.x) return true;
if (a.x > b.x) return false;
return false;
}
};
// Usage:
sort(wektor.begin(), wektor.end(), pkt_less());
这篇关于如何使用std ::排序与结构和比较函数的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!