很怀念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
17 template < class T >
18 void coutIterator1(T & );
19
20 void coutIterator2( int & );
21
22 int 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
35 template < class T >
36 void coutIterator1(T & iter) {
37 std::cout << iter << std::endl;
38}
39
40 void coutIterator2( int & i) {
41 std::cout << i << std::endl;
42}
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
17 template < class T >
18 void coutIterator1(T & );
19
20 void coutIterator2( int & );
21
22 int 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
35 template < class T >
36 void coutIterator1(T & iter) {
37 std::cout << iter << std::endl;
38}
39
40 void 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