#include <iostream>
#include <vector>
#include <algorithm> // 调用for_each时需要导入的头文件
#include <functional>
using namespace std;
void myPrint(int value) {
cout << "value: " << value << endl;
}
void test01() {
vector<int> vector1;
for (int i = 0; i < 10; i++) {
vector1.push_back(i + 1);
}
for_each(vector1.begin(), vector1.end(), myPrint);
}
class MyPrint {
public:
void operator()(int value) {
cout << "MyPrint value: " << value << endl;
}
};
void test02() {
vector<int> vector1;
for (int i = 0; i < 10; i++) {
vector1.push_back(i + 1);
}
for_each(vector1.begin(), vector1.end(), MyPrint());
}
struct MyPrintStruct {
void operator()(int value) {
cout << "MyPrintStruct value: " << value << endl;
this->count++;
}
int count = 0;
};
void test03() {
vector<int> vector1;
for (int i = 0; i < 10; i++) {
vector1.push_back(i + 1);
}
cout << "count: " << for_each(vector1.begin(), vector1.end(), MyPrintStruct()).count << endl;
}
struct MyPrint03 : public binary_function<int, int, void> {
void operator()(int value, int start) const {
cout << value + start << endl;
}
};
void test04() {
vector<int> vector1;
for (int i = 0; i < 10; i++) {
vector1.push_back(i + 1);
}
for_each(vector1.begin(), vector1.end(), bind1st(MyPrint03(), 30));
}
class Transform {
public:
int operator()(int value) {
return value + 10;
}
};
void test05() {
vector<int>vector1; // 原容器
for (int i = 0; i < 10; i++) {
vector1.push_back(i + 1);
}
vector<int>vTarget; // 目标容器
vTarget.resize(vector1.size());
transform(vector1.begin(), vector1.end(), vTarget.begin(), Transform());
for_each(vTarget.begin(), vTarget.end(), [](int value) {cout << value << endl; });
}
int main() {
//test01();
//test02();
//test03();
//test04();
test05();
return EXIT_SUCCESS;
}