文章目录
[1] 普通for_each使用仿函数
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct myPrint
{
void operator()(int i) const
{
cout << i << " ";
}
};
int main(int argc, char const *argv[]) {
int arr[5] = {0, 1, 2, 3, 4};
vector<int> ia(arr, arr + 5);
for_each(ia.begin(), ia.end(), myPrint());
cout << endl;
return 0;
}
结果:0 1 2 3 4
[1] 普通for_each使用仿函数,仿函数自带参数
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct myPrint
{
const char* val;
myPrint(const char* s): val(s){}
void operator()(int i) const
{
cout << val << i << endl;
}
};
int main(int argc, char const *argv[]) {
int arr[5] = {0, 1, 2, 3, 4};
vector<int> ia(arr, arr + 5);
for_each(ia.begin(), ia.end(), myPrint("value:"));
return 0;
}
结果:
value:0
value:1
value:2
value:3
value:4
[2] for_each使用匿名仿函数-lamda表达式
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char const *argv[]) {
int arr[5] = {0, 1, 2, 3, 4};
vector<int> ia(arr, arr + 5);
const char* str = "value: ";
for_each(ia.begin(), ia.end(), [str](int i)->void{
cout << str << i << " ";
});
cout << endl;
return 0;
}
结果:value: 0 value: 1 value: 2 value: 3 value: 4