首选标准用途:范围为或std :: for_each [英] Preferred standard use: range based for or std::for_each

查看:124
本文介绍了首选标准用途:范围为或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。

解决方案


  1. 基于范围的对于显然更容易读写。

    (虽然 std :: find_if 替换为 std :: for_each 也允许这样做。)

    li>
  2. 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.

解决方案

  1. 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 for std::for_each allows this as well.)

  2. std::for_each, ironically, is the alternative which is actually range based and allows you to select particular begin and end values instead of the whole container. (EDIT: This can be hacked around using a simple range class providing begin and end 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 to bind, 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屋!

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