Share via


for each を使用した STL コレクションの反復処理

C++ の標準ライブラリ (STL)のコレクションを反復処理するために for each のキーワードを使用できます。

すべてのプラットフォーム

解説

STL の収集は、 コンテナーです。詳細については、「STL コンテナー」を参照してください。

次のコード例は <map>を反復処理するために for each を使用します。

// for_each_stl.cpp
// compile with: /EHsc
#include <map>
#include <iostream>
#include <string>
using namespace std;

int main() {
   int retval  = 0;
   map<string, int> months;

   months["january"] = 31;
   months["february"] = 28;
   months["march"] = 31;
   months["april"] = 30;
   months["may"] = 31;
   months["june"] = 30;
   months["july"] = 31;
   months["august"] = 31;
   months["september"] = 30;
   months["october"] = 31;
   months["november"] = 30;
   months["december"] = 31;

   map<string, int> months_30;

   for each( pair<string, int> c in months )
      if ( c.second == 30 )
         months_30[c.first] = c.second;

   for each( pair<string, int> c in months_30 )
      retval++;

   cout << "Months with 30 days = " << retval << endl;
}

出力

  

次のコード例では、 STL コンテナーとの反復変数に定数の参照 (const&)を使用します。T&として宣言できる型のすべてのコレクションの反復変数として参照 (&)を使用できます。

// for_each_stl_2.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>
using namespace std;

int main() {
   int retval = 0;
      
   vector<int> col(3);
   col[0] = 10;
   col[1] = 20;
   col[2] = 30;
   
   for each( const int& c in col )
      retval += c;

   cout << "retval: " << retval << endl;
}

出力

  

Windows ランタイム

解説

この機能のプラットフォーム固有の解説がありません。

ms177203.collapse_all(ja-jp,VS.110).gif要件

コンパイラ オプション: /ZW

共通言語ランタイム

解説

この機能のプラットフォーム固有の解説がありません。

ms177203.collapse_all(ja-jp,VS.110).gif要件

コンパイラ オプション: /clr

参照

関連項目

for each、in

概念

ランタイム プラットフォームのコンポーネントの拡張機能