Preferred standard use: range based for or std::for_each

后端 未结 2 1241
臣服心动
臣服心动 2020-12-13 03:33

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 bette

2条回答
  •  粉色の甜心
    2020-12-13 04:25

    std::for_each returns the functor that has been used internally in the loop, so it provides a clean mechanism to gather some information concerning the elements in the sequence. The range based for loop is just a loop, so any state that is to be used outside of the loop has to be declared outside of that scope. In your example, if the purpose of the of the loops is to mutate each element of the sequence, then there isn't much difference at all. But if you are not using the return value of the for_each then you're probably better off with the simple loop. By the way, the range based loop works on C-style arrays and std::strings too.

    This is an example of using the return value of for_each, although it is not a very imaginative or useful one. It is just to illustrate the idea.

    #include 
    #include 
    #include 
    
    struct Foo {
      void operator()(int i) { if (i > 4) sum += i;}
      int sum{0};
    };
    
    int main() {
    
      std::array a{1,2,3,4,5,6,7,8,9,10};
      Foo foo = std::for_each(a.begin(), a.end(), Foo());
      std::cout << "Sum " << foo.sum << "\n";
    }
    

提交回复
热议问题