替换元素
替换序列内的元素
replace(beg,end,const T& oldValue,const T& newValue)
replace_if(beg,end,op,const T& newValue)
(1)replace()将区间[beg,end)之内每一个“与oldValue相等”的元素替换为newValue;
(2)replace_if()将区间[beg,end)之内每一个令以下一元判断式:op(elem) 获得true的元素替换为newValue;
(3)op不应该在函数调用过程中改变自身状态;
(4)复杂度:线性;
代码示例:
#include"fuzhu.h"
using namespace std;
int main()
{
list coll;
INSERT_ELEMENTS(coll,2,7);
INSERT_ELEMENTS(coll,4,9);
PRINT_ELEMENTS(coll,"coll: ");
replace(coll.begin(),coll.end(),6,42); // 6->42
PRINT_ELEMENTS(coll,"coll: ");
replace_if(coll.begin(),coll.end(),bind2nd(less(),5),0); // < 5 -> 0
PRINT_ELEMENTS(coll,"coll: ");
system("pause");
return 0;
}
复制并替换元素
replace_copy(sourceBeg,sourceEnd,destBeg,const T& oldValue,const T& newValue)
replace_copy_if(sourceBeg,sourceEnd,destBeg,op,const T& newValue)
代码示例:
#include"fuzhu.h"
using namespace std;
int main()
{
list coll;
INSERT_ELEMENTS(coll,2,6);
INSERT_ELEMENTS(coll,4,9);
PRINT_ELEMENTS(coll);
replace_copy(coll.begin(),coll.end(),ostream_iterator(cout," "),5,55);//5改为55,并输出
cout<(cout," "),bind2nd(less(),5),42);//小于5的变为42,并输出
cout<(cout," "),not1(bind2nd(modulus(),2)),0);//偶数变为0,并输出
cout<(cout," "),bind2nd(modulus(),2),0);//奇数变为0,并输出
cout<