c – 将传递条件作为模板参数与sort()的比较导致比将条件函数指针传递给qsort()的开销更少?

前端之家收集整理的这篇文章主要介绍了c – 将传递条件作为模板参数与sort()的比较导致比将条件函数指针传递给qsort()的开销更少?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Stroustrup的 The C++ programming language,Page 431中,当他讨论标准库的设计时,他说,

For example,building the comparison criteria into a sort function is unacceptable because the same
data can be sorted according to different criteria. This is why the C standard library qsort() takes a comparison function as an argument rather than relying on something fixed,say,the < operator. On the other hand,the overhead imposed by a function call for each comparison compromises qsort() as a building block for further library building.

以上这些对我有意义.但在第二段中,

Is that overhead serIoUs? In most cases,probably not. However,the function call overhead can
dominate the execution time for some algorithms and cause users to seek alternatives. The technique of supplying comparison criteria through a template argument described in §13.4 solves that
problem.

在§13.4中,比较标准被定义为具有静态成员函数的类(进行比较).当这些类用作模板参数时,仍然通过其静态成员函数进行比较.在我看来,仍然会有调用静态成员函数的开销.

Stroustrup的意思是什么?

解决方法

std::sort是一个功能模板.在编译期间,将为每个类型和比较运算符创建单独的排序实例.并且因为对于每个排序实例化,类型和比较器在编译时是已知的,这允许内联比较器功能并因此避免函数调用的成本.
原文链接:https://www.f2er.com/c/116804.html

猜你在找的C&C++相关文章