常用拷贝和替换算法
算法简介
copy
功能描述
函数原型
示例
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
void myPrint(int val) {
cout << val << " ";
}
void test() {
vector<int> v;
for (int i = 0; i < 5; ++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(), myPrint);
}
int main() {
test();
return 0;
}
replace
功能描述
函数原型
示例
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
void myPrint(int val) {
cout << val << " ";
}
void test() {
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(1);
v.push_back(3);
v.push_back(4);
v.push_back(1);
replace(v.begin(), v.end(), 1, 10);
for_each(v.begin(), v.end(), myPrint);
}
int main() {
test();
return 0;
}
replace_if
功能描述
函数原型
示例
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
void myPrint(int val) {
cout << val << " ";
}
class Greater30{
public:
bool operator()(int val){
return val >= 3;
}
};
void test() {
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(1);
v.push_back(3);
v.push_back(4);
v.push_back(1);
for_each(v.begin(), v.end(), myPrint);
cout << endl;
replace_if(v.begin(), v.end(),Greater30(),30);
for_each(v.begin(), v.end(), myPrint);
}
int main() {
test();
return 0;
}
swap
功能描述
函数原型
示例
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
void myPrint(int val) {
cout << val << " ";
}
class Greater30{
public:
bool operator()(int val){
return val >= 3;
}
};
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(), myPrint);
cout << endl;
for_each(v2.begin(), v2.end(), myPrint);
cout << endl;
cout << "交换后:" << endl;
v1.swap(v2);
for_each(v1.begin(), v1.end(), myPrint);
cout << endl;
for_each(v2.begin(), v2.end(), myPrint);
cout << endl;
}
int main() {
test();
return 0;
}