Foreach trong C++
C++11 giới thiệu vòng lặp foreach (range-based for) để duyệt mảng/container:
Ví dụ C++
#include <iostream>
using namespace std;
int main()
{
int myArr[] = { 99, 15, 67 };
// foreach loop
for (int ele : myArr)
cout << ele << endl;
}
Kết quả C++
99 15 67
Foreach trong C#
Foreach trong C# duyệt các phần tử trong collection (mảng, List, v.v.):
Ví dụ C#
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int[] n = new int[10];
for (int i = 0; i < 10; i++)
{
n[i] = i + 100;
}
foreach (int j in n)
{
int i = j - 100;
Console.WriteLine("Element[{0}] = {1}", i, j);
}
Console.ReadKey();
}
}
}
Kết quả C#
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109
So sánh: Cả hai đều đơn giản hóa việc duyệt tập hợp. C# foreach hoạt động trên bất kỳ type nào implement IEnumerable. C++ range-based for hoạt động trên mảng, container STL, và type có begin()/end().