Difference between Foreach and For Loops?

2020-07-18 07:11发布

What's the real difference between a foreach and for loop if either can get the same job done? I'm learning C++ and apparently there is no foreach loop for its arrays :(

6条回答
仙女界的扛把子
2楼-- · 2020-07-18 07:53

"For Each" syntax is used to iterate through a collection of objects, while a for loop is a loop that will execute for a given range. C++ does have for_each in its STL and can be used to iterate through linear object containers such as a vector.

查看更多
来,给爷笑一个
3楼-- · 2020-07-18 07:53

In other languages with a foreach construct, they're usually convenience for not having to index into the collection you're looping over. That is, you're given the next object in the collection without having access to (or need for) the index itself. If you need the index for some reason, you'll usually need the for loop, though in some languages you have access to the counter in their 'foreach'.

查看更多
小情绪 Triste *
4楼-- · 2020-07-18 08:00

as experience test , FOR is more Faster than FOREACH

查看更多
趁早两清
5楼-- · 2020-07-18 08:04

foreach generally has 1 parameter, for has 3. Anything foreach can do for can too. Part of the reason why foreach doesn't exist in C++ is because the number of iterations can't always be inferred from the type.

I believe boost library has a method of getting foreach to work, and C++11 has a range-based of for:

int my_array[5] = {1, 2, 3, 4, 5};
for (int &x : my_array) {
    x *= 2;
}
查看更多
我想做一个坏孩纸
6楼-- · 2020-07-18 08:05

There is something like for each for arrays in C++ and that is iterators. Both loops are essentially identical with the only difference being - with an ordinary for loop you have an index which you might need depending on what type of data you are accessing and whether you need to do some calculations with the index and there is (probably) an increased chance of off-by-one errors. Whereas foreach loops just guarantee that will be executed as many times as there are elements in the array without exposing an index (which you can mimic) so as a I said they are essentially the same but their usage largely depends on the way you manipulate your data.

查看更多
男人必须洒脱
7楼-- · 2020-07-18 08:11

There is no "foreach" language construct in C++, a least not literally. C++11 introduces something that's "as good as" a foreach loop, though.

The traditional for loop has something to do with evaluating conditions and performing repeated operations. It's a very general control structure. Its most popular use is to iterate over container or array contents, but that's just a tiny fraction of what you can do with it.

A "foreach" loop, on the other hand, is explicitly designed to iterate over container elements.

Example:

int arr[5] = { 1, 3, 5, 2, 4 };

for (int & n : arr) { n *= 2; } // "for-each" loop, new in C++11

for (size_t i = 0; i != 5; ++i) { arr[i] *= 2; } // "classic" for loop

In the second for, we use a traditional for loop to increment an auxiliary variable i in order to access the container arr. The first, range-based loop does not expose any details of the iteration, but just says "do this and that to each element in the collection".

Since the traditional for loop is a very general control structure, it can also be used in unusual ways:

std::vector<std::string> all_lines;
for (std::string line; std::cin >> line; all_lines.push_back(line))
{
  std::cout << "On line " << (all_lines.size() + 1) << " you said: " << line << std::endl;
}

You can trivially rewrite for(A; B; C) as a while loop:

{  // scope!
  A;
  while (true && B)
  {
    {  // more scope!
      /* for loop body */
    }
    C;
  }
}

Edit: I would probably be remiss not to mention the library function template std::for_each from <algorithm>, which in conjunction with lambdas is a very nice and self-descriptive way to iterate over arbitrary ranges (not just entire containers). It has existed since Day 1, but before lambdas it was a show-stopping pain to use.


Update: I thought of something else that might be relevant here: A "foreach" loop generally assumes that you don't modify the container. A common type of looping that modifies the container requires the traditional for-loop; as for example in this typical erase pattern:

for(Container::const_iterator it = v.begin(); it != v.end() /* not hoisted! */; /* no increment */ )
{
  // do something
  if (suitable_condition)
  {
    v.erase(it++);   // or it = v.erase(it), depending on container type
  }
  else
  {
    ++it;
  }
}
查看更多
登录 后发表回答