函数原型 //replace template<class FwdIt, class T> void replace(FwdIt first, FwdIt last, const T &vold, const & &vnew); 即:if(*(first+N)==vold) N(-[0, last - first) *(first+N) = vnew; //replace_if template<class, FwdIt, class Pred, class T> void replace_if(FwdIt first, FwdIt last, Pred pr, const T &val); 即:if(pr(*first+N)) N(-[0, last-first) *(first+N)=val //replace_copy template<class InIt, class OutIt, class T> OutIt replace_copy(InIt first, InIt last, OutIt x, const T & vold, const T & vnew) 即:if(*(first+N)==vold) N(-[0, last-first) *(x+N) = vnew; else *(x+N) = *(first+N) //repalce_copy_if template<class InIt, class OutIt, class Pred, class T> OutIt replace_copy_if(InIt first, InIt last, OutIt x, Pred pr, const T &val); 即:if(pr(*(first+N))) N(-[0,last-first) *(x+N)=val; else *(x+N)=(first+N) replace replace_if replace_copy replace_copy_if #include <iostream> #include <iterator> #include <cstdlib> #include <vector> using namespace std; int main(int argc, char argv[]) { int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; cout << "原始数据为/t/t a[10] = " ; copy(a, a+10, ostream_iterator<int>(cout, " ")); cout << endl; vector<int> v1(a, a+10); replace(v1.begin(), v1.end(), 2, 4); cout << "2->4后为/t/tv1[10] = " ; copy(v1.begin(), v1.end(), ostream_iterator<int>(cout, " ")); cout << endl; vector<int> v2(a, a+10); replace_if(v2.begin(), v2.end(), bind2nd(less<int>(),4),9); cout << "(<4)->9后为/t/tv2[10] = " ; copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " ")); cout << endl; vector<int> v3(a, a+10); vector<int> v4; replace_copy(v3.begin(), v3.end(), back_inserter(v4), 4, 30); cout << "原始数据4用30替换-->/tv4[10] = "; copy(v4.begin(), v4.end(), ostream_iterator<int>(cout, " ")); cout << endl; vector<int> v5(a, a+10); vector<int> v6; replace_copy_if(v5.begin(), v5.end(), back_inserter(v6), bind2nd(less<int>(), 4), 30); cout << "原始数据低于4用30替换:/tv6[10] = "; copy(v6.begin(), v6.end(), ostream_iterator<int>(cout, " ")); cout << endl; system("pause"); return 0; }