代码如下:
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
using namespace std;void myPrint(int val)
{cout << val << " ";
}void test01()
{vector<int>v1;for (int i = 0; i < 10; i++){v1.push_back(i + 1);}vector<int>v2;v2.resize(v1.size());copy(v1.begin(), v1.end(), v2.begin());for_each(v2.begin(), v2.end(), myPrint);cout << endl;
}int main()
{test01();return 0;
}
测试结果:
总结:
代码如下:
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
using namespace std;void myPrint(int val)
{cout << val << " ";
}void test01()
{vector<int>v1;for (int i = 0; i < 10; i++){v1.push_back(i + 1);}for_each(v1.begin(), v1.end(), myPrint);cout << endl;replace(v1.begin(), v1.end(), 2, 2000);for_each(v1.begin(), v1.end(), myPrint);cout << endl;
}int main()
{test01();return 0;
}
测试结果:
总结:
代码如下:
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
using namespace std;void myPrint(int val)
{cout << val << " ";
}class replaceGreater30
{
public:bool operator()(int val){return val >= 30;}
};void test01()
{vector<int>v1;for (int i = 20; i <= 40; i++){v1.push_back(i + 1);}for_each(v1.begin(), v1.end(), myPrint);cout << endl;replace_if(v1.begin(), v1.end(), replaceGreater30(),3000);for_each(v1.begin(), v1.end(), myPrint);cout << endl;
}int main()
{test01();return 0;
}
测试结果:
总结:
代码如下:
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
using namespace std;void myPrint(int val)
{cout << val << " ";
}class replaceGreater30
{
public:bool operator()(int val){return val >= 30;}
};void test01()
{vector<int>v1;vector<int>v2;for (int i = 0; i <= 10; i++){v1.push_back(i);v2.push_back(i + 100);}for_each(v1.begin(), v1.end(), myPrint);cout << endl;for_each(v2.begin(), v2.end(), myPrint);cout << endl;cout << "-------------------------------------" << endl;swap(v1, v2);for_each(v1.begin(), v1.end(), myPrint);cout << endl;for_each(v2.begin(), v2.end(), myPrint);cout << endl;
}int main()
{test01();return 0;
}
测试结果:
总结: