常用拷贝和替换算法
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//复制拷贝
void print(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
for_each(v.begin(), v.end(), print);
cout << endl;
vector<int>v2;
v2.resize(v.size());
copy(v.begin(), v.end(), v2.begin());
for_each(v2.begin(), v2.end(), print);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
//总结:利用cpy算法是,目标容器记得提前开辟空间
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
void print(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v;
v.push_back(20);
v.push_back(50);
v.push_back(30);
v.push_back(70);
v.push_back(20);
v.push_back(20);
cout << "替换前" << endl;
for_each(v.begin(), v.end(), print);
cout << endl;
cout << "替换后" << endl;
replace(v.begin(), v.end(), 20, 10000);
for_each(v.begin(), v.end(), print);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
//总结:replace会替换区间内所以满足条件的元素
#include <iostream>
using namespace std;
#include<vector>
#include<algorithm>
//按条件查找,替换所有满足条件
class Print {
public:
void operator()(int val)
{
cout << val << " ";
}
};
class Greate30 {
public:
bool operator()(int val)
{
return val > 30;
}
};
void test01()
{
vector<int> v;
v.push_back(10);
v.push_back(43);
v.push_back(45);
v.push_back(67);
v.push_back(27);
v.push_back(74);
v.push_back(16);
v.push_back(78);
cout << "替换前" << endl;
for_each(v.begin(), v.end(), Print());
cout << endl;
cout << "替换后" << endl;
//将大于30的替换为4000
replace_if(v.begin(), v.end(), Greate30(), 4000);
for_each(v.begin(), v.end(), Print());
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
#include <iostream>
using namespace std;
#include<vector>
#include<algorithm>
//按条件查找,替换所有满足条件
class Print {
public:
void operator()(int val)
{
cout << val << " ";
}
};
void test01()
{
vector<int> v;
vector<int> v2;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
v2.push_back(i + 1000);
}
cout << "交换前" << endl;
for_each(v.begin(), v.end(), Print());
cout << endl;
for_each(v2.begin(), v2.end(), Print());
cout << endl;
cout << "交换后" << endl;
swap(v, v2);
for_each(v.begin(), v.end(), Print());
cout << endl;
for_each(v2.begin(), v2.end(), Print());
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
//总结:swap交换容器时,交换容器要是同等类型
本文作者: 永生
本文链接: https://yys.zone/detail/?id=100
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!
发表评论
评论列表 (0 条评论)
暂无评论,快来抢沙发吧!