loop for array container

Hi, I m new to the C++ and got stuck with follwoing assignment question.
Which three different loop forms is best suited for processing the elements of an array container? Justify your answer.

I think the answer is
Array container are part of the STL(standard template library of c++) the three major ways to itearte over the array containers

1) For loop

2) for each loop

3) iterator


However, I cannot find online or textbook to justify that they are the best loop form for array container.



Well, they are really the only way. I'm assuming you mean looping by index, by iterator and using the C++11 ranged for loop - std::for_each works a bit differently, applying a function to every object in the range.

So, I'd say you should have:
1
2
3
4
5
6
7
8
9
10
std::array<int, 5> arr = {0, 1, 2, 3, 4};

for (std::size_t i = 0; i < arr.size(); ++i)
    std::cout << arr[i] << " ";
// OR
for (auto it = arr.begin(); it != arr.end(); ++it)
    std::cout << *it << " ";
// OR
for (auto x : arr)
    std::cout << x << " ";
One thing to add:

1
2
for (auto& x : arr)
    std::cout << x << " ";


You could use a reference in this range-based for loop if you want to actually change each element.
Topic archived. No new replies allowed.