您的位置:首页 > 编程语言 > Go语言

Why use sort() when we have "good old qsort()"?

2007-02-23 08:21 387 查看
To a novice,
qsort(array,asize,sizeof(elem),elem_compare);

looks pretty weird, and is harder to understand than
sort(vec.begin(),vec.end());

To an expert, the fact that sort() tends to be faster than qsort() for the same elements and the same comparison criteria is often significant. Also, sort() is generic, so that it can be used for any reasonable combination of container type, element type, and comparison criterion. For example:
struct Record {
string name;
// ...
};

struct name_compare {	// compare Records using "name" as the key
bool operator()(const Record& a, const Record& b) const
{ return a.name<b.name; }
};

void f(vector<Record>& vs)
{
sort(vs.begin(), vs.end(), name_compare());
// ...
}

In addition, most people appreciate that sort() is type safe, that no casts are required to use it, and that they don't have to write a compare() function for standard types.

For a more detailed explanation, see my paper "Learning C++ as a New language", which you can download from my publications list.

The primary reason that sort() tends to outperform qsort() is that the comparison inlines better.  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息