Foreach in C++ and JAVA
The foreach loop is used to quickly iterate over the elements of a container (array, vectors, etc.) without performing initialization, testing, or increment/decrement. Foreach loops work by doing something for each element rather than doing something n times. Although there is no foreach loop in C, it is supported by C++ and Java. It was first introduced in C++ in C++ 11, and in Java in JDK 1.5.0. In both C++ and Java, the keyword for foreach loop is "for."
We no longer need to specify the data type for variables in foreach loops thanks to the introduction of the auto keyword in C++ and the var keyword in Java. Type inference detects the data type of the container and sets the variable used for traversing to the same data type.
The code below demonstrates the use of a foreach loop for various containers, as well as the auto/var keywords in C++/Java.
Traversing the array with foreach using array's data type: 10 20 30 40 Traversing the array with foreach using auto keyword : 10 20 30 40
Vector C++ programme:
Traversing the vector with foreach using vector's data type: This is foreach example using vector. Traversing the vector with foreach using auto keyword : This is foreach example using vector.
C++/Java Set Program:
Traversing the set with foreach using set's data type: 1 2 4 5 6 7 10 Traversing the set with foreach using auto keyword : 1 2 4 5 6 7 10
For array, vector, and set, we can use different data types in foreach.
C++/Java Map Program:
Traversing the map with foreach using map's data type 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example Traversing the map with foreach using auto keyword 1 Geeks 2 4 3 Geeks 4 Map 5 Foreach 6 Example
Foreach loop has the following advantages:
Foreach loop has the following disadvantage:
Next TopicC++ templates vs. Java generics