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.
本文对比了C++中qsort()与sort()函数的使用方法及性能表现,详细介绍了sort()函数的优势及其类型安全特性,并通过实例展示了如何为自定义结构体实现特定排序规则。
160

被折叠的 条评论
为什么被折叠?



