How to do For Each Loops in C++

For Each loops, or loops that go through every element in an array, can be written two ways in C++ and Visual Studio. You can write it similar to C# like this:

for each (int item in numberList)
{
     std::cout << "Current value: " << item << std::endl;
}

However, the more common way to write them and recommended by Microsoft is to use a range-based for loop like so:

for (auto item : numberList)
{
     std::cout << "Current value: " << item << std::endl;
}

Both methods achieve the same result, however, range-based for loops can optionally also be given a set range, rather than looping through the entire list.

In this example, however, both loops go through the entire array of ints called numberList, printing out their values to the console.

It goes in the format of:

foreach ( type_of_variable    iterator_name    in    array_to_search)
{
     iterator_name = something;
}

When you do this kind of foreach loop, you are declaring the type of variable you want to search for in the array. It has to be the same variable type that’s contained in the array. You then give an iterator name, so that whenever you refer to that iterator, you are referring to the current element in the array that you’ve looped to. Effectively:

std::cout << "Current value: " << item << std::endl;

is the same as

std::cout << "Current value: " << numberList[i] << std::endl;

The iterator ‘item’ becomes the value you have looped to. In other words, referring to the iterator is the equivalent of a regular for loop like this:

for (int i = 0; i < numberList.size(); i++)
{
     std::cout << "Item: " << numberList[i] << std::endl;
}

For Each loops will work on many different types of arrays such as standard arrays, vectors, lists and others. You can even use the range-based for loop on unordered maps.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s