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

来源:互联网 发布:win10看不到mac分区 编辑:程序博客网 时间:2024/05/17 00:55
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 keybool 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.  

原创粉丝点击