問題描述
感謝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;
向量<包>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::sort 與結構向量和比較函數一起使用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!