這段代碼循環遍歷輸出vector中的每一個數,并判斷這個數是奇數還是偶數。我們可以隨時修改Lambda表達式而改變這個匿名函數的實現,修改對集合的操作。在這段代碼中,C++使用一對中括號“[]”來表示Lambda表達式的開始,其后的”(int n)”表示Lambda表達式的參數。這些參數將在Lambda表達式中使用到。為了體會Lambda表達式的簡潔,我們來看看同樣的功能,如何使用函數對象實現:
- #include "stdafx.h"
- #include <algorithm>
- #include <iostream>
- #include <ostream>
- #include <vector>
- using namespace std;
- struct LambdaFunctor {
- void operator()(int n) const {
- cout << n << " ";
- if (n % 2 == 0) {
- cout << " even ";
- } else {
- cout << " odd ";
- }
- }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- vector<int> v;
- for (int i = 0; i < 10; ++i) {
- v.push_back(i);
- }
- for_each(v.begin(), v.end(), LambdaFunctor());
- cout << endl;
- return 0;
- }
- #include "stdafx.h"
- #include <algorithm>
- #include <iostream>
- #include <ostream>
- #include <vector>
- using namespace std;
- struct LambdaFunctor {
- void operator()(int n) const {
- cout << n << " ";
- if (n % 2 == 0) {
- cout << " even ";
- } else {
- cout << " odd ";
- }
- }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- vector<int> v;
- for (int i = 0; i < 10; ++i) {
- v.push_back(i);
- }
- for_each(v.begin(), v.end(), LambdaFunctor());
- cout << endl;
- return 0;
- }
延伸閱讀
文章來源于領測軟件測試網 http://www.kjueaiud.com/