在stl容器中使用比较函数
为什么我可以这样做:
stable_sort(it1, it2, binary_function);
但不能这样做:
priority_queue<type, vector<type>, binary_function> pq;
为什么我可以在第一种情况下使用函数,但在第二种情况下需要一个对象?
Why can I do this:
stable_sort(it1, it2, binary_function);
but not this:
priority_queue<type, vector<type>, binary_function> pq;
Why can I use a function in the first case, but need an object in the second?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
priority_queue
是一个模板,它需要一个类型作为参数,其中binary_function
是一个函数对象。priority_queue
is a template and it expects a type as an argument, where isbinary_function
is a function object.如果您查看
std::stable_sort
上的参考,您将看到您提供的binary_function
也应该是一个函数对象...两者之间没有区别,除了在第二种情况下可能没有进行正确的“强制转换”或转换从函数到适当的函数对象。我相信这可能是由于
*sort
函数直接立即使用函子,因此如果调用*sort
函数时函数地址有效,它将在函数调用期间有效。当创建使用 this 作为数据成员(实质上)的容器时,您无法确定函数引用在容器对象的生命周期内会变得无效。我知道这是一个松散的挥手解释,但这是我能想到的最好的解释。也许在 C++ 中,对二进制函数的引用会隐式转换为 std::function 的构造,以便函数被“复制”并且不存在有效性问题。我希望现在我还没有失去你...
If you check out the reference on
std::stable_sort
, you will see that thebinary_function
you provided, should be a function object as well... There is no difference between the two, except that maybe in the second case there is no proper "cast" or conversion made from a function to a proper function object.I believe this may be due to the fact that
*sort
functions use the functor directly, and immediately, thus if the function address is valid when the*sort
function is called, it will be valid for the duration of the function call. When creating a container that uses this as a data member (in essence), you can't be sure the function reference will become invalidated during the lifetime of the container object. I know it's a loose handwaving explication, but it's the best I can come up with. Perhaps in C++ the reference to a binary function will be implicitely converted to the construction of astd::function
so that the function is "copied" and there is no validity problem.I hope I haven't lost you now...