C++ foreach Loop
π C++ foreach Loop (Range-Based for Loop)
C++ mein foreach loop ko officially range-based for loop kehte hain.
Ye arrays, strings, vectors, lists, maps jaise collections ke har element par iterate karne ka simple aur clean tareeqa hai.
Introduced in C++11
Β 1. Syntax
-
variableβ har iteration mein current element -
collectionβ array / string / vector etc.
Β 2. Array Example
Output:
Β 3. String Example
Output:
Β 4. Vector Example
Β 5. Using auto (Recommended)
β Cleaner code
β Type automatically detected
Β 6. Modify Elements (Use Reference &)
β This will NOT change original values:
β Correct way:
Β 7. Read-Only Loop (Use const)
β Safe
β Faster for large data
Β 8. foreach vs Normal for
Range-based for |
Normal for |
|---|---|
| Short & clean | More control |
| No index needed | Index available |
| Less error-prone | Flexible |
Β 9. When NOT to Use foreach β
-
Jab index ki zarurat ho
-
Jab partial loop (start/end control) chahiye
-
Jab step size custom ho
β Common Mistake
β Correct:
π Summary
-
Foreach = range-based
forloop -
Best for arrays, strings, STL containers
-
Use
auto+const &for best practice -
Simple, readable & safe looping
