logo

C++ 및 Java의 Foreach

Foreach 루프 초기화, 테스트 및 증가/감소를 수행하지 않고 컨테이너의 요소(배열, 벡터 등)를 빠르게 반복하는 데 사용됩니다. foreach 루프의 작동 방식은 어떤 작업을 n번 수행하는 것이 아니라 모든 요소에 대해 작업을 수행하는 것입니다. C에는 foreach 루프가 없지만 C++와 Java 모두 foreach 유형의 루프를 지원합니다. C++에서는 C++ 11과 JDK 1.5.0의 Java에 도입되었습니다. foreach 루프에 사용되는 키워드는 다음과 같습니다. ~을 위한 C++와 Java 모두에서.

통사론:

for (data_type variable_name : container_name) { operations using variable_name }>

C++의 auto 키워드와 Java의 var 키워드가 도입되면서 더 이상 foreach 루프의 변수에 대한 데이터 유형을 지정할 필요가 없습니다. 유형 추론은 컨테이너의 데이터 유형을 감지하고 탐색에 사용되는 변수에 동일한 데이터 유형을 자동으로 설정합니다.

아래 코드는 다양한 컨테이너에 대한 foreach 루프의 사용 사례를 표시합니다. 자동/림 키워드 C++/자바 .

C++/자바 프로그램 배열의 경우:

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 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+>' '>);> >}> }>

>

>

산출

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>

벡터용 C++ 프로그램:

C++


데이터 링크 계층 프로토콜



#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;> }>

>

if-else 자바

>

산출

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.>

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 +>' '>);> >}> >}> }>

>

>

산출

3 24 -134 -2 100>

세트용 C++/Java 프로그램:

C++




#include> #include> using> namespace> std;> int> main() {> >set<>int>>값 = {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; }>

>

>

자바




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+>' '>);> >}> > >}> }>

>

>

산출

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>

메모: foreach에서는 배열, 벡터 및 집합에 대해 서로 다른 데이터 유형을 사용할 수 있습니다.

지도용 C++/Java 프로그램:

C++14


페이지다운 키보드



#include> #include> using> namespace> std;> int> main() {> >map<>int>, string>지도예;> >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 : 지도예제 ) {> >cout<' '< } cout<<' Traversing the map with foreach using auto keyword '; for (auto mpEx : mapExample){ cout<' '< } return 0; }>

>

>

자바




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());> >}> }>

>

>

산출

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 루프의 장점:

  • 코드를 더 읽기 쉽게 만듭니다.
  • 데이터 초과 실행 또는 부족 실행 오류를 제거합니다.

foreach 루프의 단점:

  • 요소를 역순으로 반복할 수 없습니다.
  • 각각의 모든 요소에 액세스할 수 있으며 그 사이의 요소를 건너뛸 수 없습니다.