1.常用拷贝和替换算法
算法简介:
copy容器内指定范围元素拷贝到另一个容器中replace将容器内指定范围的旧元素修改为新元素replace_if容器内指定范围满足条件的元素替换为新元素swap互换两个容器的元素2.copy将容器指定范围的元素拷贝到另一容器中/*函数原型:copy(iteratorbeg,iteratorend,iteratordest);把指定范围内的元素拷贝到指定容器内beg开始迭代器end结束迭代器dest指定容器的开始迭代器*/voidmyPrint(intval){coutval"";}voidtest01(){vectorintv;v.push_back(10);v.push_back(0);v.push_back(50);v.push_back(20);v.push_back(40);vectorintv2;//对于指定容器要提前开辟空间v2.resize(v.size());//拷贝copy(v.begin(),v.end(),v2.begin());for_each(v2.begin(),v2.end(),myPrint);}intmain(){test01();system("pause");return0;}2.replace将指定容器内指定范围的旧元素修改为新元素
/*函数原型:replace(iteratorbeg,iteratorend,oldvalue,newvalue);将区间内旧元素替换成新元素beg开始迭代器end结束迭代器oldvalue旧元素newvalue新元素*/voidmyPrint(intval){coutval"";}voidtest01(){vectorintv;v.push_back(10);v.push_back(0);v.push_back(50);v.push_back(20);v.push_back(40);cout"替换前:"endl;for_each(v.begin(),v.end(),myPrint);cout"替换后:"endl;replace(v.begin(),v.end(),20,);for_each(v.begin(),v.end(),myPrint);//替换前:////替换后://1005040}intmain(){test01();system("pause");return0;}.replace_if将区间内满足条件的元素,替换成指定元素
/*函数原型:replace_if(iteratorbeg,iteratorend,_pred,newvalue);按条件替换,满足条件的替换成指定元素beg开始迭代器end结束迭代器_pred谓词newvalue新元素*/voidmyPrint(intval){coutval"";}classGreat0{public:booloperater()(intval){returnval=0;}};voidtest01(){vectorintv;v.push_back(10);v.push_back(0);v.push_back(50);v.push_back(20);v.push_back(40);//将大于等于0替换为cout"替换前:"endl;for_each(v.begin(),v.end(),myPrint);cout"替换后:"endl;replace_if(v.begin(),v.end(),Great0(),);for_each(v.begin(),v.end(),myPrint);}intmain(){test01();system("pause");return0;}4.swap互换两个容器的元素
/*函数原型:swap(containerc1,containerc2);互换两个容器的元素注意:互换的两个容器必须是同类型的c1容器1c2容器2*/voidmyPrint(intval){coutval"";}voidtest01(){vectorintv1;vectorintv2;for(inti=0;i10;i++){v1.push_back(i);v2.push_back(i+);}cout"交换前:"endl;for_each(v1.begin(),v1.end(),myPrint);coutendl;for_each(v2.begin(),v2.end(),myPrint);coutendl;cout"交换后:"endl;swap(v1,v2);for_each(v1.begin(),v1.end(),myPrint);coutendl;for_each(v2.begin(),v2.end(),myPrint);}intmain(){test01();system("pause");return0;}