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

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

概述在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 t 在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是一个功能模板.在编译期间,将为每个类型和比较运算符创建单独的排序实例.并且因为对于每个排序实例化,类型和比较器在编译时是已知的,这允许内联比较器功能并因此避免函数调用的成本. 总结

以上是内存溢出为你收集整理的c – 将传递条件作为模板参数与sort()的比较导致比将条件函数指针传递给qsort()的开销更少?全部内容,希望文章能够帮你解决c – 将传递条件作为模板参数与sort()的比较导致比将条件函数指针传递给qsort()的开销更少?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1236252.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存