藉由使用每個反覆查看 STL 集合

for each關鍵字可用來逐一查看標準 C++ 程式庫 (STL) 集合。

所有平台

備註

STL 集合也就是會容器。如需詳細資訊,請參閱 STL 容器

範例

範例

下列程式碼範例使用for each來進行反覆<map>

// 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;
}

Output

  

範例

下列程式碼範例會使用 const 參考 (const&) 與 STL 容器的反覆項目變數。您可以使用參考 (&) 反覆運算變數的型別,可以宣告為任何集合成 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;
}

Output

  

Windows 執行階段

備註

有這項功能沒有平台特定性質備註。

ms177203.collapse_all(zh-tw,VS.110).gif需求

編譯器選項:/ZW

Common Language Runtime

備註

有這項功能沒有平台特定性質備註。

ms177203.collapse_all(zh-tw,VS.110).gif需求

編譯器選項:/clr

請參閱

參考

針對每一個,在

概念

執行階段平台的元件擴充功能