次の方法で共有


方法: それぞれのの 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 参照 (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 ランタイム

解説

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

要件

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

共通言語ランタイム

解説

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

要件

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

参照

関連項目

各について、

概念

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