C++之常用的拷贝和替换算法
C++之常用的拷贝和替换算法
copy
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
void Myptint(int val)
{
cout << val << " ";
}
void test()
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector<int>v2;
v2.resize(v.size());
copy(v.begin(), v.end(), v2.begin());
for_each(v2.begin(), v2.end(), Myptint);
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}
replace
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
void Myptint(int val)
{
cout << val << " ";
}
void test()
{
vector<int> v;
v.push_back(10);
v.push_back(30);
v.push_back(50);
v.push_back(20);
cout << "替换前" << endl;
for_each(v.begin(), v.end(), Myptint);
cout << endl;
//将50替换为500
replace(v.begin(), v.end(), 50, 500);
cout << "替换后" << endl;
for_each(v.begin(), v.end(), Myptint);
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}
replace_if
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
void Myptint(int val)
{
cout << val << " ";
}
class Greater30
{
public:
bool operator()(int val)
{
return val >= 30;
}
};
void test()
{
vector<int> v;
v.push_back(10);
v.push_back(30);
v.push_back(50);
v.push_back(20);
cout << "替换前" << endl;
for_each(v.begin(), v.end(), Myptint);
cout << endl;
//将大于等于30替换为500
replace_if(v.begin(), v.end(), Greater30(), 500);
cout << "替换后" << endl;
for_each(v.begin(), v.end(), Myptint);
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}
swap
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
void Myptint(int val)
{
cout << val << " ";
}
void test()
{
vector<int> v;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
v2.push_back(i + 10);
}
cout << "交换前" << endl;
for_each(v.begin(), v.end(), Myptint);
cout << endl;
for_each(v2.begin(), v2.end(), Myptint);
cout << endl;
swap(v, v2);
cout << "交换后" << endl;
for_each(v.begin(), v.end(), Myptint);
cout << endl;
for_each(v2.begin(), v2.end(), Myptint);
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}