简体   繁体   English

在stl容器中使用比较函数

[英]using comparison function in stl container

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? 为什么我可以在第一种情况下使用函数,但在第二种情况下需要一个对象?

priority_queue是一个模板,它期望一个类型作为参数,其中binary_function是一个函数对象。

If you check out the reference on std::stable_sort , you will see that the binary_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. 如果你看看std::stable_sort上的引用,你会看到你提供的binary_function也应该是一个函数对象......两者之间没有区别,除了可能在第二种情况下没有正确的“强制转换”或从函数转换为适当的函数对象。

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. 我相信这可能是因为*sort函数直接使用仿函数,因此如果函数地址在调用*sort函数时有效,它将在函数调用期间有效。 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 a std::function so that the function is "copied" and there is no validity problem. 也许在C ++中,对二进制函数的引用将被隐含地转换为std::function的构造,以便该函数被“复制”并且没有有效性问题。

I hope I haven't lost you now... 我希望我现在没有失去你...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM