.\" ident @(#)replace.3 .\" Standard Template Library .\" $$RW_INSERT_HEADER "slyrs.man" .TH replace 3C++ "02 Apr 1998" "Rogue Wave Software" "-" .ce2 Standard C++ Library Copyright 1998, Rogue Wave Software, Inc. .SH NAME \f2replace\fP \ - Substitutes elements in a collection with new values. .SH SYNOPSIS .br #include .br template .br void replace (ForwardIterator first, .RE .RS 13 ForwardIterator last, .br const T& old_value, .br const T& new_value); .SH DESCRIPTION For the range \f2[first, last)\fP, the replace algorithm replaces elements referred to by iterator \f2i\fP with \f2new_value\fP, when the following condition holds: \f2*i == old_value\fP. .SH COMPLEXITY Exactly \f2last - first\fP comparisons or applications of the corresponding predicate are done. .SH EXAMPLE .RE .RS 0 // .br // replace.cpp .br // .RE .RS 1 #include .br #include .br #include .br #include .RE .RS 0 using namespace std; .br .br template .br struct all_true : public unary_function .RE .RS 1 { .RE .RS 2 bool operator()(const Arg&){ return 1; } .RE .RS 1 }; .RE .RS 0 .br int main() .RE .RS 1 { .RE .RS 0 .RE .RS 3 //Initialize a vector with an array of integers .RE .RS 2 int arr[10] = {1,2,3,4,5,6,7,8,9,10}; .br vector v(arr, arr+10); .RE .RS 0 .RE .RS 3 //Print out original vector .RE .RS 2 cout << "The original list: " << endl << " "; .br copy(v.begin(),v.end(),ostream_iterator .RE .RS 7 (cout," ")); .RE .RS 2 cout << endl << endl; .RE .RS 0 .RE .RS 3 //Replace the number 7 with 11 .br replace(v.begin(), v.end(), 7, 11); .RE .RS 0 .br .RE .RS 3 // Print out vector with 7 replaced, .br // s.b. 1 2 3 4 5 6 11 8 9 10 .RE .RS 2 cout << "List after replace " << endl << " "; .br copy(v.begin(),v.end(),o .RE .RS 7 stream_iterator(cout," ")); .RE .RS 2 cout << endl << endl; .RE .RS 0 .RE .RS 3 //Replace 1 2 3 with 13 13 13 .RE .RS 2 replace_if(v.begin(), v.begin()+3, all_true(), 13); .RE .RS 0 .RE .RS 3 // Print out the remaining vector, .br // s.b. 13 13 13 4 5 6 11 8 9 10 .RE .RS 2 cout << "List after replace_if " << endl << " "; .br copy(v.begin(),v.end(), .RE .RS 7 ostream_iterator(cout," ")); .RE .RS 2 cout << endl << endl; .RE .RS 0 .RE .RS 2 return 0; .RE .RS 1 } .br .RE .RS 0 Program Output .RE .RS 0 .br The original list: .RE .RS 4 1 2 3 4 5 6 7 8 9 10 .RE .RS 0 List after replace: .RE .RS 4 1 2 3 4 5 6 11 8 9 10 .RE .RS 0 List after replace_if: .RE .RS 4 13 13 13 4 5 6 11 8 9 10 .RE .RS 0 List using replace_copy to cout: .RE .RS 4 17 17 17 4 5 6 11 8 9 10 .RE .RS 0 List with all elements output as 19s: .RE .RS 4 19 19 19 19 19 19 19 19 19 19 .SH WARNINGS If your compiler does not support default template parameters, then you always need to supply the \f2Allocator\fP template argument. For instance, you need to write: \f2vector >\fP instead of: \f2vector\fP If your compiler does not support namespaces, then you do not need the using declaration for \f2std\fP. .SH SEE ALSO replace_if, replace_copy, replace_copy_if