算法简介:
函数原型:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//copy——拷贝算法
void Print(int val)
{
cout << val << " ";
}
void test()
{
vector<int>v1;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
}
v2.resize(v1.size());
copy(v1.begin(), v1.end(), v2.begin());
for_each(v2.begin(), v2.end(), Print);
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}
函数原型:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//replace——替换算法
class Print
{
public:
void operator()(int val)
{
cout << val << " ";
}
};
void test()
{
vector<int>v;
v.push_back(10);
v.push_back(70);
v.push_back(60);
v.push_back(90);
v.push_back(80);
v.push_back(40);
v.push_back(80);
cout << "替换前:" << endl;
for_each(v.begin(), v.end(), Print());
cout << endl;
replace(v.begin(), v.end(), 80, 800);
cout << "替换后:" << endl;
for_each(v.begin(), v.end(), Print());
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}
?注:replace会替换区间内满足条件的所有元素。
函数原型:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//replace_if——替换算法
class Print
{
public:
void operator()(int val)
{
cout << val << " ";
}
};
class Greater20
{
public:
bool operator()(int val)
{
return val >= 20;
}
};
void test()
{
vector<int>v;
v.push_back(10);
v.push_back(40);
v.push_back(30);
v.push_back(50);
v.push_back(60);
v.push_back(20);
v.push_back(50);
cout << "替换前:" << endl;
for_each(v.begin(), v.end(), Print());
cout << endl;
replace_if(v.begin(), v.end(), Greater20(), 2000);
cout << "替换后:" << endl;
for_each(v.begin(), v.end(), Print());
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}
函数原型:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//swap——替换算法
void Print(int val)
{
cout << val << " ";
}
void test()
{
vector<int>v1;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i + 100);
}
cout << "互换前: " << endl;
for_each(v1.begin(), v1.end(), Print);
cout << endl;
for_each(v2.begin(), v2.end(), Print);
cout << endl;
cout << "互换后: " << endl;
swap(v1, v2);
for_each(v1.begin(), v1.end(), Print);
cout << endl;
for_each(v2.begin(), v2.end(), Print);
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}
注:swap交换的容器需要同种类型