在stl容器中使用比较函数

发布于 2024-10-07 21:55:37 字数 235 浏览 0 评论 0原文

为什么我可以这样做:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡淡の花香 2024-10-14 21:55:37

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

priority_queue is a template and it expects a type as an argument, where is binary_function is a function object.

╰沐子 2024-10-14 21:55:37

如果您查看 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 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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文