简体   繁体   中英

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.

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 a std::function so that the function is "copied" and there is no validity problem.

I hope I haven't lost you now...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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