目录
●copy
●replace
●replace_if
●swap
●copy
1.功能描述:
将容器内指定范围的元素拷贝到另一容器中
2.查看copy定义下底层代码的函数原型:
3.向deque容器中插入10~50五个数,将这五个数拷贝到另一个指定容器中并输出。
#include<iostream>
#include<deque>
#include<algorithm>
using namespace std;
void printdeque(int value)
{
cout << value << " ";
}
void text()
{
deque<int>d;
d.push_back(10);
d.push_back(20);
d.push_back(30);
d.push_back(40);
d.push_back(50);
for_each(d.begin(), d.end(), printdeque);
cout << endl;
deque<int>d1;
d1.resize(d.size());
copy(d.begin(),d.end(),d1.begin());
for_each(d1.begin(),d1.end(),printdeque);
}
int main()
{
text();
}
●replace
1.功能描述:
将容器内指定的旧元素改为新元素
2.查看replace定义下底层代码的函数原型:
3.向deque容器中插入1~10十个元素,使用replace算法去指定容器中已有的旧元素和将要替换旧元素的新元素并输出。
#include<iostream>
#include<deque>
#include<algorithm>
using namespace std;
void printdeque(int value)
{
cout << value << " ";
}
void replace_func(deque<int>&d1)
{
cout << "请输入要修改的旧值:";
int n_old; cin >> n_old;
cout << "请输入要修改的新值:";
int n_new; cin >> n_new;
replace(d1.begin(), d1.end(), n_old, n_new);
cout << "替换后:";
for_each(d1.begin(), d1.end(), printdeque);
}
void text()
{
deque<int>d1;
for (int i = 1; i <= 10; i++)
{
d1.push_back(i);
}
cout << "替换前:";
for_each(d1.begin(),d1.end(),printdeque);
cout << endl;
replace_func(d1);
}
int main()
{
text();
}
●replace_if
1.功能描述:
将容器内满足条件的元素,替换成指定元素
2.查看replace_if定义下底层代码的函数原型:
3.向deque容器中插入1~10十个元素,使用replace_if条件替换算法去指定一个大于6的条件谓词,输入指定将要替换旧元素的新元素并输出。
#include<iostream>
#include<deque>
#include<algorithm>
using namespace std;
void printdeque(int value)
{
cout << value << " ";
}
class compare {
public:
bool operator()(const int value)
{
return value > 6;
}
};
void replace_if_func(deque<int>&d)
{
cout << "请输入要修改的新值:";
int n_new; cin >> n_new;
replace_if(d.begin(),d.end(),compare(),n_new);
cout << "替换后:";
for_each(d.begin(), d.end(), printdeque);
}
void text()
{
deque<int>d;
for (int i = 1; i <= 10; i++)
{
d.push_back(i);
}
cout << "替换前:";
for_each(d.begin(),d.end(),printdeque);
cout << endl;
replace_if_func(d);
}
int main()
{
text();
}
●swap
1.功能描述:
互换两个容器的元素(同类型容器)
2.查看swap定义下底层代码的函数原型:
3.分别向deque容器中插入1~10和11~20,使用swap交换算法交换两容器中前后的内容并且输出。
#include<iostream>
#include<deque>
#include<algorithm>
using namespace std;
void printdeque(int value)
{
cout << value << " ";
}
void swap_func(deque<int>&d1, deque<int>&d2)
{
cout << "交换前" << endl;
swap(d1, d2);
cout << "d1:"; for_each(d1.begin(), d1.end(), printdeque);
cout << endl;
cout << "d2:"; for_each(d2.begin(), d2.end(), printdeque);
cout << endl;
}
void text()
{
deque<int>d1;
deque<int>d2;
for (int i = 1, j = 1, k=11; i <= 10; i++, j++,k++)
{
d1.push_back(j);
d2.push_back(k);
}
cout << "交换前"<<endl;
cout << "d1:"; for_each(d1.begin(),d1.end(),printdeque);
//1 2 3 4 5 6 7 8 9 10
cout << endl;
cout << "d2:"; for_each(d2.begin(),d2.end(),printdeque);
//11 12 13 14 15 16 17 18 19 20
cout << endl;
swap_func(d1,d2);
}
int main()
{
text();
}