C++/CLI 是微軟為 .NET 平台設計的 C++ 延伸,提供 `for each` 關鍵字,用於遍歷實現 `IEnumerable` 的集合。語法:
for each (type item in collection) { ... }
#include "stdafx.h"
using namespace System;
int main(array^ args) {
int vowels = 0, consonants = 0;
String^ proverb = L"A nod is as good as a wink to a blind horse.";
for each (wchar_t ch in proverb) {
if (Char::IsLetter(ch)) {
ch = Char::ToLower(ch);
switch (ch) {
case L'a': case L'e': case L'i': case L'o': case L'u':
++vowels; break;
default:
++consonants; break;
}
}
}
Console::WriteLine(proverb);
Console::WriteLine(L"The proverb contains {0} vowels and {1} consonants.", vowels, consonants);
Console::ReadLine();
return 0;
}
// C++/CLI
for each (wchar_t ch in proverb) { ... }
// 標準 C++11 (範圍-based for)
for (wchar_t ch : proverb) { ... } // 需 proverb 為 std::wstring 或數組
// 標準 C++98 (迭代器)
for (auto it = proverb.begin(); it != proverb.end(); ++it) { ... }