首选标准用途:范围为或std :: for_each [英] Preferred standard use: range based for or std::for_each
问题描述
在 C ++ 11 中,所有元素都有两个循环(范围基于for和for_each )。有任何理由比任何一个更喜欢一个,还是有一个更好的情况?
for(auto& elem :container){
//使用elem
执行操作}
std :: for_each(container.begin(),container.end,
[] ; elem){
//与elem
}做某事);
我的想法是,第一个更简单,类似于其他语言的基于范围的循环,而second也适用于不是完整容器的序列,第二个更类似于其他 std
-algorithms。
-
基于范围的
(虽然对于
显然更容易读写。std :: find_if
替换为std :: for_each
也允许这样做。) li>
std :: for_each
,实际上是基于范围的选择,允许您选择特定的begin
和end
值,而不是整个容器。 ( EDIT:这可以使用一个简单的范围
类提供begin
code> end 成员,例如由Boost提供。)
还有
for_each
可能更优雅,否则使用高阶函数:它可以用作bind
的参数,第三个参数已经是函子。
主要是风格问题。大多数读者可能更喜欢看(auto& a:b)
,大多数实现现在支持它。
In C++11, there are two loops over all elements (range based for and for_each). Is there any reason to prefer one over the other or are there situations where one is a better fit?
for (auto& elem: container) {
// do something with elem
}
std::for_each(container.begin(), container.end,
[](Elem& elem) {
// do something with elem
});
My idea would be that the first is simpler and is similar to range based loops in other languages while the second also works for sequences that are not complete containers and the second is more similar to other std
-algorithms.
Range-based
for
is obviously simpler to read and write. It is specialized for this task.EDIT: You can break form a range-for without abusing an exception. (Although
std::find_if
substituted forstd::for_each
allows this as well.)std::for_each
, ironically, is the alternative which is actually range based and allows you to select particularbegin
andend
values instead of the whole container. (EDIT: This can be hacked around using a simplerange
class providingbegin
andend
members, such as provided by Boost.)Also
for_each
may be more elegant when otherwise using higher-order functions: it can be used as an argument tobind
, and the third argument is already a functor.
Mainly it's a matter of style. Most readers probably prefer to see for ( auto &a : b )
though, and most implementations now support it.
这篇关于首选标准用途:范围为或std :: for_each的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!