問(wèn)題描述
感謝C 中的解決方案,現(xiàn)在我想在 C++ 中使用 std::sort 和 vector 來(lái)實(shí)現(xiàn)這一點(diǎn):
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() 填充;比較函數(shù):
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
中使用的比較函數(shù)不同的比較函數(shù).該函數(shù)不返回 –1、0 或 1,而是返回一個(gè) bool
值,指示第一個(gè)元素是否小于第二個(gè)元素.
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.
您有兩種可能性:為您的對(duì)象實(shí)現(xiàn) operator <
;在這種情況下,沒(méi)有第三個(gè)參數(shù)的默認(rèn) sort
調(diào)用將起作用;或者你可以重寫(xiě)上面的函數(shù)來(lái)完成同樣的事情.
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.
請(qǐng)注意,您必須在參數(shù)中使用強(qiáng)類(lèi)型.
Notice that you have to use strong typing in the arguments.
另外,這里根本不使用函數(shù)也不錯(cuò).相反,使用函數(shù)對(duì)象.這些受益于內(nèi)聯(lián).
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());
這篇關(guān)于如何將 std::sort 與結(jié)構(gòu)向量和比較函數(shù)一起使用?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!