Foreach bucle s'utilitza per iterar sobre els elements d'un contenidor (matriu, vectors, etc.) ràpidament sense realitzar inicialització, prova i increment/disminució. El funcionament dels bucles foreach és fer alguna cosa per a cada element en lloc de fer alguna cosa n vegades. No hi ha cap bucle foreach en C, però tant C++ com Java admeten el tipus de bucle foreach. En C++, es va introduir en C++ 11 i Java en JDK 1.5.0. La paraula clau utilitzada per al bucle foreach és per tant en C++ com en Java.
Sintaxi:
for (data_type variable_name : container_name) { operations using variable_name }> Amb la introducció de la paraula clau auto en C++ i la paraula clau var a Java, ja no hem d'especificar el tipus de dades per a la variable al bucle foreach. La inferència de tipus detecta el tipus de dades del contenidor i estableix automàticament el mateix tipus de dades a la variable utilitzada per a la travessa.
El codi següent mostra el cas d'ús del bucle foreach per a diferents contenidors juntament amb auto/lim paraules clau dins C++/Java .
Programa C++/Java per a la matriu:
C++
// C++ program to demonstrate use of foreach for array> #include> using> namespace> std;> int> main()> {> >int> arr[] = { 10, 20, 30, 40 };> >// Printing elements of an array using> >// foreach loop> >// Here, int is the data type, x is the variable name> >// and arr is the array for which we want to iterate foreach> >cout<<>'Traversing the array with foreach using array's data type: '>;> >for> (>int> x : arr)> >cout<' '; // data type of x is set as int cout<<'
Traversing the array with foreach using auto keyword : '; for (auto x : arr) cout<' '; }> |
>
>
Java
// Java program to demonstrate use of foreach> public> class> Main {> >public> static> void> main(String[] args)> >{> >// Declaring 1-D array with size 4> >int> arr[] = {>10>,>20>,>30>,>40> };> >// Printing elements of an array using> >// foreach loop> >// Here, int is the data type, x is the variable name> >// and arr is the array for which we want to iterate foreach> >System.out.print(>'Traversing the array with foreach using array's data type: '>);> >for> (>int> x : arr)> >System.out.print(x+>' '>);> > >// data type of x is set as int> >System.out.print(>'
Traversing the array with foreach using auto keyword : '>);> >for> (var x : arr)> >System.out.print(x+>' '>);> >}> }> |
>
>Sortida
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>
Programa C++ per a vectors:
C++
tipus de dades de referència en java
#include> #include> using> namespace> std;> int> main()> {> >vector value{>'This'>,>'is'>,>'foreach'>,> >'example'>,>'using'>,>'vector.'> };> >cout <<>'Traversing the vector with foreach using '> >'vector's data type: '>;> >for> (string v : value) {> >cout << v <<>' '>;> >}> >cout <<>'
Traversing the vector with foreach using '> >'auto keyword : '>;> >for> (>auto> v : value)> >cout << v <<>' '>;> >return> 0;> }> |
>
>Sortida
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.>
Programa Java per a ArrayList:
Java
/*package whatever //do not write package name here */> import> java.util.*;> class> GFG {> >public> static> void> main(String[] args)> >{> >ArrayList list =>new> ArrayList();> >list.add(>3>);> >list.add(>24>);> >list.add(->134>);> >list.add(->2>);> >list.add(>100>);> >for> (>int> element : list) {> >System.out.print(element +>' '>);> >}> >}> }> |
>
>Sortida
3 24 -134 -2 100>
Programa C++/Java per al conjunt:
C++
#include> #include> using> namespace> std;> int> main() {> >set<>int>>valor = {6, 2, 7, 4, 10, 5, 1};> > >cout<<>'Traversing the set with foreach using set's data type: '>;> >for> (>int> v : value) {> >cout<' '; } cout<<'
Traversing the set with foreach using auto keyword : '; for (auto v : value) cout<' '; return 0; }> |
>
>
Java
c matriu de cadenes
import> java.util.*;> > public> class> GFG {> > >public> static> void> main(String[] args)> >{> >Set hash_Set =>new> HashSet();> >hash_Set.add(>'Geeks'>);> >hash_Set.add(>'For'>);> >hash_Set.add(>'Geeks'>);> >hash_Set.add(>'Foreach'>);> >hash_Set.add(>'Example'>);> >hash_Set.add(>'Set'>);> > >System.out.print(>'Traversing the set with foreach using set's data type: '>);> >for>(String hs : hash_Set) {> >System.out.print(hs+>' '>);> >}> > >System.out.print(>'
Traversing the set with foreach using auto keyword : '>);> >for> (var hs : hash_Set) {> >System.out.print(hs+>' '>);> >}> > >}> }> |
>
>Sortida
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>
Nota: Podem utilitzar diferents tipus de dades a foreach per a matriu, vector i conjunt.
Programa C++/Java per al mapa:
C++14
#include> #include> using> namespace> std;> int> main() {> >map<>int>, string>mapExample;> >mapExample.insert(pair<>int>, string>(1,>'Geeks'>));> >mapExample.insert(pair<>int>, string>(2,>'4'>));> >mapExample.insert(pair<>int>, string>(3,>'Geeks'>));> >mapExample.insert(pair<>int>, string>(4,>'Map'>));> >mapExample.insert(pair<>int>, string>(5,>'Foreach'>));> >mapExample.insert(pair<>int>, string>(6,>'Example'>));> > >cout<<>'Traversing the map with foreach using map's data type
'>;> >for> (pair<>int>, string>mpEx : mapExample ) {> >cout<' '< } cout<<'
Traversing the map with foreach using auto keyword
'; for (auto mpEx : mapExample){ cout<' '< } return 0; }> |
>
>
Java
delimitador java
import> java.io.*;> import> java.util.Map;> import> java.util.HashMap;> class> GFG {> >public> static> void> main (String[] args) {> >Map gfg =>new> HashMap();> > >gfg.put(>1>,>'Geeks'>);> >gfg.put(>2>,>'4'>);> >gfg.put(>3>,>'Geeks'>);> >gfg.put(>4>,>'Map'>);> >gfg.put(>5>,>'Foreach'>);> >gfg.put(>6>,>'Example'>);> > >System.out.println(>'Traversing the map with foreach using map's data type'>);> >for> (Map.Entry entry : gfg.entrySet())> >System.out.println(entry.getKey() +>' '> + entry.getValue());> > >System.out.println(>'
Traversing the map with foreach using auto keyword'>);> >for> (var entry : gfg.entrySet())> >System.out.println(entry.getKey() +>' '> + entry.getValue());> >}> }> |
>
>Sortida
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>
Avantatges del bucle foreach:
- Fa que el codi sigui més llegible.
- Elimina els errors de sobreexecució o subexecució de les dades.
Desavantatge del bucle foreach:
- No es pot iterar sobre els elements en ordre invers.
- S'accedirà a tots i cadascun dels elements, no es pot saltar cap element intermedi.