|
| 1 | +## lambda函数 |
| 2 | +```C++ |
| 3 | +#include <iostream> |
| 4 | +#include <vector> |
| 5 | +#include <algorithm> |
| 6 | +#include <functional> |
| 7 | +using namespace std; |
| 8 | + |
| 9 | +int greater1(int firstVal, int secondVal) { |
| 10 | + return firstVal > secondVal ? true : false; |
| 11 | +} //greater是保留字 |
| 12 | + |
| 13 | +void findSpecificValue(const std::vector<int>& vec, int specificValue) { |
| 14 | + auto iter = vec.begin(); |
| 15 | + iter = find_if(iter, vec.end(), std::bind(greater1, std::placeholders::_1, specificValue)); |
| 16 | + if (iter != vec.end()) { |
| 17 | + cout << "greater than" << specificValue << ":" << *iter << endl; |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +int main() { |
| 22 | + vector<int> vec{ 1,2,3,4,5,6,7,8,9,10 }; |
| 23 | + findSpecificValue(vec, 8); |
| 24 | + system("pause"); |
| 25 | + return 0; |
| 26 | +} |
| 27 | + |
| 28 | + |
| 29 | +``` |
| 30 | +修改为`lambda`形式,只能输出`9` |
| 31 | +```C++ |
| 32 | +#include <iostream> |
| 33 | +#include <vector> |
| 34 | +#include <algorithm> |
| 35 | +#include <functional> |
| 36 | +using namespace std; |
| 37 | +
|
| 38 | +bool greater(int firstVal, int secondVal) { |
| 39 | + return firstVal > secondVal ? true : false; |
| 40 | +} |
| 41 | +
|
| 42 | +void findSpecificValue(const std::vector<int>& vec, int specificValue) { |
| 43 | + auto iter = vec.begin(); |
| 44 | + while (iter != vec.end()) { |
| 45 | + iter = find_if(iter, vec.end(), [specificValue](const int &a) {return a > specificValue; }); |
| 46 | + if (iter != vec.end()) { |
| 47 | + cout << "greater than" << specificValue << ":" << *iter << endl; |
| 48 | + } |
| 49 | + iter++; |
| 50 | + } |
| 51 | +} |
| 52 | +
|
| 53 | +int main() { |
| 54 | + vector<int> vec{ 1,2,3,4,5,6,7,8,9,10 }; |
| 55 | + findSpecificValue(vec, 8); |
| 56 | + system("pause"); |
| 57 | + return 0; |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +## String |
| 62 | +```C++ |
| 63 | + |
| 64 | +``` |
0 commit comments