C++/STL Algorithms Modifying sequence operations/replace copy
std::replace_copy
<source lang="cpp">
- include <iostream>
using std::cout; using std::endl;
- include <algorithm>
- include <vector>
- include <iterator>
int main() {
int a[ 10 ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 }; std::ostream_iterator< int > output( cout, " " ); std::vector< int > v2( a, a + 10 ); // copy of a std::vector< int > c1( 10 ); // instantiate vector c1 cout << "Vector v2 before replacing all 10s and copying:\n "; std::copy( v2.begin(), v2.end(), output ); // copy from v2 to c1, replacing 10s with 100s std::replace_copy( v2.begin(), v2.end(), c1.begin(), 10, 100 ); cout << "\nVector c1 after replacing all 10s in v2:\n "; std::copy( c1.begin(), c1.end(), output ); cout << endl; return 0;
}
/*
Vector v2 before replacing all 10s and copying:
10 2 10 4 16 6 14 8 12 10
Vector c1 after replacing all 10s in v2:
100 2 100 4 16 6 14 8 12 100 */ </source>
Use replace_copy to print all elements with value 5 replaced with 55
<source lang="cpp">
/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */
- include <iostream>
- include <vector>
- include <deque>
- include <list>
- include <set>
- include <map>
- include <string>
- include <algorithm>
- include <iterator>
- include <functional>
- include <numeric>
/* PRINT_ELEMENTS()
* - prints optional C-string optcstr followed by * - all elements of the collection coll * - separated by spaces */
template <class T> inline void PRINT_ELEMENTS (const T& coll, const char* optcstr="") {
typename T::const_iterator pos; std::cout << optcstr; for (pos=coll.begin(); pos!=coll.end(); ++pos) { std::cout << *pos << " "; } std::cout << std::endl;
} /* INSERT_ELEMENTS (collection, first, last)
* - fill values from first to last into the collection * - NOTE: NO half-open range */
template <class T> inline void INSERT_ELEMENTS (T& coll, int first, int last) {
for (int i=first; i<=last; ++i) { coll.insert(coll.end(),i); }
} using namespace std; int main() {
list<int> coll; INSERT_ELEMENTS(coll,2,6); INSERT_ELEMENTS(coll,4,9); PRINT_ELEMENTS(coll); // print all elements with value 5 replaced with 55 replace_copy(coll.begin(), coll.end(), // source ostream_iterator<int>(cout," "), // destination 5, // old value 55); // new value cout << endl;
}
/*
2 3 4 5 6 4 5 6 7 8 9 2 3 4 55 6 4 55 6 7 8 9
*/ </source>