如果一个preFER STL算法过手卷循环?手卷、算法、preFER、STL

2023-09-11 04:29:30 作者:吃可爱长大

我似乎看到更多的for循环在以上问题及放迭代器;答案在这里比我的for_each(),变换(),和类似物。斯科特迈尔斯表明 STL算法是preferred ,或者至少,他在2001年当然做了,使用起来经常意味着移动循环体成一个函数或函数对象。有些人可能会觉得这是一个无法接受的并发症,而另一些人可能会觉得它下来的问题,更好地休息。

I seem to be seeing more 'for' loops over iterators in questions & answers here than I do for_each(), transform(), and the like. Scott Meyers suggests that stl algorithms are preferred, or at least he did in 2001. Of course, using them often means moving the loop body into a function or function object. Some may feel this is an unacceptable complication, while others may feel it better breaks down the problem.

所以...应该STL算法是pferred过手卷循环$ P $?

So... should STL algorithms be preferred over hand-rolled loops?

推荐答案

这取决于:

高性能是否需要 循环的可读性 不管是算法复杂

如果循环不是瓶颈,算法很简单(如的for_each),那么对于当前的C ++标准,我倒是preFER一个手卷循环的可读性。 (逻辑的地点是关键。)

If the loop isn't the bottleneck, and the algorithm is simple (like for_each), then for the current C++ standard, I'd prefer a hand-rolled loop for readability. (Locality of logic is key.)

然而,现在的C ++ 0x / C ++ 11的支持,一些重大的编译器,我会说使用STL算法,因为他们现在允许拉姆达EX pressions - 因而逻辑的地方

However, now that C++0x/C++11 is supported by some major compilers, I'd say use STL algorithms because they now allow lambda expressions — and thus the locality of the logic.