C++ foreach Loop: Explained with Examples

C++ foreach loop explained with examples

Purpose of foreach loop in C++ and a few facts

  • “Foreach” loop (also range-based for loop) is a way to iterate through the arrays, vectors, or other datasets/ranges in C++.
  • The C++ “foreach” loop enables traversing through the elements of containers (Vector, array, lists, maps, etc.) without performing the normal requirements of the for loop. For example, initialization, condition, and incrementing or decrementing the value.
  • There is no keyword “foreach” in C++. (See the syntax below for how it is written.)
  • The for each loop is designed to perform something for each element rather than executing for loop to do something n times.
  • Due to the “foreach” keyword popularity in different programming languages e.g. PHP foreach, C# foreach, this is searched/used for C++ in that way.
  • It was only in C++11 that “foreach” loop was introduced, released in the year 2011.

Syntax of foreach loop in C++

This is the general way of writing the foreach loop in C++:

for(type range-declaration: array/vector_name)

{

Statements to execute here

}

How for each loops works in C++?

  • Range-declaration is the name of variable.
  • It’s data type is the type of element of sequence (array, vector, map, etc.)
  • Since C++ introduced the auto keyword, we are no longer required to specify the data type of the variable.
  • The array or vector etc. that you want to traverse is specified.
  • Inside the body of for loop, the statements to be executed are written.

An example of using the range-based loop

In this example, an array of five elements is created.

The array is of integer type and we assigned the values at the time of declaration.

Then we used for loop to iterate through its elements as follows:

#include <iostream>

using namespace std;


int main() {

   int numArr[] = { 5, 10, 15, 20, 25 };

   // Using for loop (foreach) to traverse through array

   for (int x : numArr)

   //Display current array element

   cout << x << endl;

}

Output:

5
10
15
20
25

Using string array example

Similarly, you may traverse through a string array by using foreach loop in C++. Have a look:

#include <iostream>

using namespace std;

int main() {

   string strArr[4] = {"Banana", "Apple", "Mango", "Orange"};


   // Using for loop (foreach) to traverse through a string array

   for (string x : strArr)

   //Display current string array element

   cout << x << "\n";

}

Output:

Banana
Apple
Mango
Orange

In the program:

  • We declared a string array of four elements.
  • Then we used a for loop where a string variable is declared to hold the array element value.
  • The string array is also specified in the for loop.
  • In the for loop body, we displayed the current element of the array

Using auto type declaration example

As mentioned earlier, with the introduction of auto keyword in C++, you do not need to specify the data type variable in foreach loop.
The data type of the array or other container (vector, map, etc.) is detected by the type interface.

It sets the same data type of the variable used in the for loop.

An example below shows how:

#include <iostream>

using namespace std;

int main() {

   string animalsArr[4];

    animalsArr[0] = "Lion";
    animalsArr[1] = "Tiger";
    animalsArr[2] = "Bear";
    animalsArr[3] = "Wolf";

   // Using for loop (foreach) to traverse through a string array

   for (auto ani : animalsArr)

   //Display current string array element

   cout << ani << "\n";

}

Output:

Lion
Tiger
Bear
Wolf

The example of traversing through a vector using C++ for each

In this example, we used a vector in the for each loop:

#include<iostream>

#include<vector>

using namespace std;

int main()

{

    //Declaring and assigning values to a vector

    vector<int> numVec={5,10,15,20,25};

    //Foreach loop to traverse through vector
    for(int num : numVec)

    {
      cout<<num<<"\n";
    }

    return 0;
}

Output:

5
10
15
20
25

In the program:

  • A vector of five int type elements is created
  • This vector is used in the foreach loop
  • The data type of the traversing variable is set as int. You may also set it as auto.
  • Inside the for loop body, we displayed the current element of the vector.

A CPP program of list with foreach loop

You may also use the foreach loop with the list in C++. In the example below, we have created a list of four elements.

Then a for loop is used to traverse through that list and display its elements:

#include <iostream>

#include <list>

using namespace std;

int main() {

  //Declaring a list

  list<string> birds = { "Eagle", "Sparrow", "Crow", "Vulture" };

    cout <<"The List Elements Are:\n#####################\n\n";

    for (auto str: birds) {
        cout << str << "\n";

    }

}

Output:

The List Elements Are:
#####################Eagle
Sparrow
Crow
Vulture

The example with a map with foreach loop

The last example of our C++ foreah tutorial shows using it with the map.

We created a map and then displayed its key/value pairs by using the foreach look as follows:

#include <iostream>

#include <map>

using namespace std;

int main() {

    map<std::string, int> marks {

        {"Physics", 95},
        {"Chemistry", 93},
        {"Bio", 88},
        {"Maths", 100}

    };

    for (auto item: marks) {
        cout << item.first << ": " << item.second << endl;
    }
}

Output:

CPP-foreach-map

 

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!