참고 : Vector Container Iterating 속도 비교(http://npteam.net/775)

VS2005부터는 for each, in 키워드를 지원한다.
for each 문은 C#이나 JAVA 5 버전부터 지원하는 키워드이나 VS2005부터 지원한다. C++ 표준은 아직 아니고 MS Specific 이다.
MS의 for each 문은 향상된 for 문으로 STL이나 CLR의 Collection을 지원한다. 하지만 안타깝게도 VS2005부터 사용되는 ATL Collection Classes 는 지원하지 않는다.
그래서 Native C++을 사용한다면 STL에서 밖에 사용하지 못 할 것 같다. 다음은 stl에서 사용 예이다.
 

[std::vector 사용 예]

#pragma region std::vector
// 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;
}
#pragma endregion std::vector

[std::map 사용 예]

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

int main() 
{
  int retval  = 0;
  map<const char*, 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<const char*, int> months_30;

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

  for each( pair<const char*, int> c in months_30 )
    retval++;

  cout << "Months with 30 days = " << retval << endl;
}
#pragma endregion std::map

Related Posts

답글 남기기

이메일 주소는 공개되지 않습니다.