gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:14:08 27 4
gpt4 key购买 nike

在 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是一个函数模板。在编译期间,将为每个类型和比较运算符创建一个单独的 sort 实例。因为对于每个 sort 实例化,类型和比较器在编译时都是已知的,所以这允许内联比较器函数,从而避免函数调用的成本。

关于c++ - 与将条件作为模板参数传递给 sort() 的比较结果比将条件函数指针传递给 qsort() 的开销更少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25965661/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com