(原創) 如何使用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
4
Filename : GenericAlgo_for_each.cpp
5
Compiler : Visual C++ 8.0 / ISO C++
6
Description : Demo how to use for_each algorithm.
7
Release : 12/10/2006
8
*/
9
10
#include <iostream>
11
#include <vector>
12
#include <algorithm>
13
14
void cOut(const int&);
15
16
int main() {
17
std::vector<int> ivec(3,1);
18
19
for_each(ivec.begin(), ivec.end(), cOut);
20
21
return 0;
22
}
23
24
void cOut(const int &i) {
25
std::cout << i << std::endl;
26
}
/* 2
(C) OOMusou 2006 http://oomusou.cnblogs.com3

4
Filename : GenericAlgo_for_each.cpp5
Compiler : Visual C++ 8.0 / ISO C++6
Description : Demo how to use for_each algorithm.7
Release : 12/10/20068
*/9

10
#include <iostream>11
#include <vector>12
#include <algorithm>13

14
void cOut(const int&);15

16
int main() {17
std::vector<int> ivec(3,1);18

19
for_each(ivec.begin(), ivec.end(), cOut);20

21
return 0;22
}23

24
void cOut(const int &i) {25
std::cout << i << std::endl;26
}
執行結果
1
1
2
1
3
1
12
13
1


浙公网安备 33010602011771号