为什么std :: transform不保证顺序(但是for_each保证顺序)?这不是为了技巧而实现的技巧吗? [英] Why std::transform doesn't guarantee the order (but for_each guarantee the order)? Doesn't this allow trick implementation for performance?

查看:119
本文介绍了为什么std :: transform不保证顺序(但是for_each保证顺序)?这不是为了技巧而实现的技巧吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是意识到标准并不能保证在 std :: transform 中应用函数回调的顺序。而且它不允许回调函数或函子产生副作用。但是同时 std :: for_each 实际上保证了顺序。

I just realize the standard doesn't guarantee the order of applying function callback in std::transform. And it doesn't allow the callback function or functor have side effect. But at the same time std::for_each actually guarantee the order.

一个猜测是转换可以使用高性能算法,它不能保证顺序,但是O(N)已经是最好的算法。

One guess is the transform can using high performance algorithm which doesn't guarantee order, But O(N) is the best algorithm already.

所以,为什么标准不能使从应用回调函数顺序的角度来看,transform 是否具有 for_each 的行为?用户将从此保证中受益。

So why the standard doesn't make the transform have the behavior as for_each from the view of apply callback function order? The user will benefit form this guarantee.

推荐答案

此非限制性定义允许并行计算。一个实现可以选择使用多个线程来应用变换函数。另请参阅相关问题: STL算法和并发编程

This non-restrictive definition allows for parallel computing. An implementation may choose to apply transform function using several threads. See also related question: STL algorithms and concurrent programming

将其视为算法上的语义差异(也就是说,它代表了程序员的意图,而不仅仅是其他工具)。使用 for_each ,您需要进行顺序扫描。使用 transform ,您声明只需要对容器中的每个项目应用一个函数,但是您并不关心它将如何完成。

Think of it as a semantic difference in algorithms (that is, that represents programmer's intent rather than being just another tool). With for_each you state that you need a sequential scan. With transform you state that you only need to aply a function to every item in the container, but you don't care how it will be done.

这篇关于为什么std :: transform不保证顺序(但是for_each保证顺序)?这不是为了技巧而实现的技巧吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆