Vedant Dixit
Vedant Dixit

Reputation: 168

Should I use qsort over sort in C++?

I have browsed through most of the questions on the comparison between qsort vs sort in C++. I wanted to just ask if there were any cases where you would prefer qsort over sort?

Upvotes: 4

Views: 1295

Answers (3)

Malcolm McLean
Malcolm McLean

Reputation: 6404

qsort requires the comparison function to return negative, zero or positive as an integer, dependent on the ordering. Sort requires a boolean equivalent to the < operator.

Therefore if comparing floating point fields, or non-trivial requirements for structures, qsort() can demand a slightly less efficient and harder to write comparison function. Also, qsort doesn't take a context pointer, it is mpossible to sort in a context-dependent manner (something you only rarely require), without using a global. sort can take a lambda with a capture list. sort() is easier to use and can be more efficient, so is preferable, unless backwards compatibility with C is an issue.

Upvotes: 1

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275976

If you have data whose size is dynamic yet global, writing a sort for qsort is easier than for sort.

If you have code that already works with qsort, rewriting it can take work.

I haven't found another reason.

Upvotes: 1

Minor Threat
Minor Threat

Reputation: 2095

Probably none, std::sort is type safe, plus it can inline the comparator function. The only distinctive strong point of qsort is that it's available in plain C.

Upvotes: 8

Related Questions