很懷念VB和C#的foreach文法嗎?對於C++只能用for文法造成程式冗長覺得很煩嗎?foreach的確對於container而言非常好用且精簡,C++/CLI已經增加上了for each文法了,事實上,C++也可使用foreach喔,STL提供了for_each() algorithm,可以彌補這個缺憾。
for_each() algorithm會將每個iterator當作const iterator處理,若只用普通的function,直接將function name傳入即可,別忘了function name本身也是個pointer,若要用template function,則必須將該template function轉成function pointer才可傳進for_each algorithm,以下範例demo for_each() algorithm的用法。
1/**//*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : GenericAlgo_for_each.cpp
5Compiler : Visual C++ 8.0
6Description : Demo how to use for_each algorithm.
7 Applies a specified function object to each element
8 in a forward order within a range and returns the
9 function object.
10Release : 11/19/2006
11*/
12
13#include <iostream>
14#include <vector>
15#include <algorithm>
16
17template <class T>
18void coutIterator1(T &);
19
20void coutIterator2(int &);
21
22int main() {
23 std::vector<int> ivec(3,1);
24
25 void (*pf) (int &) = coutIterator1;
26 for_each(ivec.begin(), ivec.end(), pf);
27
28 std::cout << std::endl;
29
30 for_each(ivec.begin(), ivec.end(), coutIterator2);
31
32 return 0;
33}
34
35template <class T>
36void coutIterator1(T &iter) {
37 std::cout << iter << std::endl;
38}
39
40void coutIterator2(int &i) {
41 std::cout << i << std::endl;
42}
for_each() algorithm不能修改iterator,若要修改iterator,需用transform() algorithm。
See Also
(原創) 如何正確的使用迴圈(使用for_each)? (C/C++) (STL) (template)
Reference
C++ Primer 3rd中文版 P.1145