(原創) 如何使用for_each() algorithm? (C/C++) (STL)

C++沒有提供foreach語法(C++/CLI增加了for each語法了),但提供了for_each() algorithm,BS曾說,為了C++語言本身的穩定,C++語言本身不太容易變動,所以若要變也是從Library下手,有了for_each() algorithm,其實也達到其他語言foreach的功能了。

for_each()和transform()有什麼差別呢?簡單的說,for_each()是唯讀的,而transform()是可修改的,for_each()不會理會funtion的傳回值,而transform()會將傳回值變成container的element,而達到修改的效果。

 1/* 
 2(C) OOMusou 2006 http://oomusou.cnblogs.com
 3
 4Filename    : GenericAlgo_for_each.cpp
 5Compiler    : Visual C++ 8.0 / ISO C++
 6Description : Demo how to use for_each algorithm.
 7Release     : 12/10/2006
 8*/

 9
10#include <iostream>
11#include <vector>
12#include <algorithm>
13
14void cOut(const int&);
15
16int main() {
17  std::vector<int> ivec(3,1);
18
19  for_each(ivec.begin(), ivec.end(), cOut);
20
21  return 0;
22}

23
24void cOut(const int &i) {
25  std::cout << i << std::endl;
26}


執行結果

11
21
31

posted on 2006-12-10 04:10  真 OO无双  阅读(817)  评论(0编辑  收藏  举报

导航