С++ для начинающих

Алгоритм replace_copy()


template< class InputIterator, class InputIterator,

          class Type >

OutputIterator

replace_copy( InputIterator first, InputIterator last,

              class OutputIterator result,

              const Type& old_value, const Type& new_value );

replace_copy() ведет себя так же, как replace(), только новая последовательность копируется в контейнер, начиная с result. Возвращаемый итератор указывает на элемент, расположенный за последним скопированным. Исходный контейнер остается без изменения.

#include <algorithm>

#include <vector>

#include <iostream.h>

/* печатается:

   исходная последовательность:

   Christopher Robin Mr. Winnie the Pooh Piglet Tigger Eeyore



   последовательность после применения replace():

   Christopher Robin Pooh Piglet Tigger Eeyore

*/

          

int main()

{

           string oldval( "Mr. Winnie the Pooh" );

           string newval( "Pooh" );

                 

     ostream_iterator< string >  ofile( cout, " " );

           string sa[] = {

                  "Christopher Robin", "Mr. Winnie the Pooh",

                  "Piglet", "Tigger", "Eeyore"

     };

           vector< string, allocator > vec( sa, sa+5 );

     cout << "исходная последовательность:\n";

     copy( vec.begin(), vec.end(), ofile ); cout << '\n';

                 

           replace( vec.begin(), vec.end(), oldval, newval );

                 

     cout << "последовательность после применения replace():\n";

     copy( vec.begin(), vec.end(), ofile ); cout << '\n';

           vector< string, allocator > vec2;

           replace_copy( vec.begin(), vec.end(),

                   inserter( vec2, vec2.begin() ),

                   newval, oldval );

                 

     cout << "последовательность после применения replace_copy():\n";

     copy( vec.begin(), vec.end(), ofile ); cout << '\n';

}



Содержание раздела