C++/STL Algorithms Modifying sequence operations/copy

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Beginning and Ending Iterators of C-Style Arrays

<source lang="cpp">

  1. include <algorithm>
  2. include <iostream>
  3. include <iterator>

using namespace std; int main( ) {

  const int num_costs = 4;
  const float cost[num_costs] = { 11.11, 22.22, 33.33, 44.44 };
  copy( cost, cost + num_costs,ostream_iterator<float>( cout, "     " ) );
  const char* fruit[] = { "A", "B", "C" };
  copy( fruit, fruit + sizeof( fruit ) / sizeof( fruit[0] ),
     ostream_iterator<const char*>( cout, "    " ) );
  int year[] = { 2001, 2002, 2003, 2004, 2005 };
  const int num_years = sizeof( year ) / sizeof( year[0] );
  copy( year, year + num_years,ostream_iterator<int>( cout, "    " ) );
  sort( year, year + num_years );
  copy( year, year + num_years,ostream_iterator<int>( cout, "    " ) );
  reverse( year, year + num_years );
  copy( year, year + num_years,ostream_iterator<int>( cout, "    " ) );

}


 </source>


Copy all letters three elements behind the "f"

<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.
*/
  1. include <iostream>
  2. include <vector>
  3. include <deque>
  4. include <list>
  5. include <set>
  6. include <map>
  7. include <string>
  8. include <algorithm>
  9. include <iterator>
  10. include <functional>
  11. include <numeric>

using namespace std; /* 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);
   }

} int main() {

   /* initialize source collection with ""..........abcdef..........""
    */
   vector<char> source(10,".");
   for (int c="a"; c<="f"; c++) {
       source.push_back(c);
   }
   source.insert(source.end(),10,".");
   PRINT_ELEMENTS(source,"source: ");
   // copy all letters three elements in front of the "a"
   vector<char> c1(source.begin(),source.end());
   copy (c1.begin()+10, c1.begin()+16,  // source range
         c1.begin()+7);                 // destination range
   PRINT_ELEMENTS(c1,"c1:     ");
   // copy all letters three elements behind the "f"
   vector<char> c2(source.begin(),source.end());
   copy_backward (c2.begin()+10, c2.begin()+16,  // source range
                  c2.begin()+19);                // destination range
   PRINT_ELEMENTS(c2,"c2:     ");

} /* source: . . . . . . . . . . a b c d e f . . . . . . . . . . c1: . . . . . . . a b c d e f d e f . . . . . . . . . . c2: . . . . . . . . . . a b c a b c d e f . . . . . . .

*/        
   
 </source>


Copy and insert list

<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.
*/
  1. include <iostream>
  2. include <vector>
  3. include <list>
  4. include <deque>
  5. include <set>
  6. include <algorithm>

using namespace std; int main() {

   list<int> coll1;
   // insert elements from 1 to 9 into the first collection
   for (int i=1; i<=9; ++i) {
       coll1.push_back(i);
   }
   // copy the elements of coll1 into coll2 by appending them
   vector<int> coll2;
   copy (coll1.begin(), coll1.end(),      // source
         back_inserter(coll2));           // destination
   // copy the elements of coll1 into coll3 by inserting them at the front
   // - reverses the order of the elements
   deque<int> coll3;
   copy (coll1.begin(), coll1.end(),      // source
         front_inserter(coll3));          // destination
   // copy elements of coll1 into coll4
   // - only inserter that works for associative collections
   set<int> coll4;
   copy (coll1.begin(), coll1.end(),      // source
         inserter(coll4,coll4.begin()));  // destination

}


 </source>


Copy istream_iterator to ostream_iterator

<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.
*/
  1. include <iostream>
  2. include <algorithm>
  3. include <iterator>
  4. include <string>

using namespace std; int main() {

   copy (istream_iterator<string>(cin),         // beginning of source
         istream_iterator<string>(),            // end of source
         ostream_iterator<string>(cout,"\n"));  // destination

} /* a a Terminate batch job (Y/N)? n

*/        
   
 </source>


Copy vector and list

<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.
*/
  1. include <iostream>
  2. include <vector>
  3. include <list>
  4. include <deque>
  5. include <algorithm>

using namespace std; int main() {

   list<int>   coll1;
   vector<int> coll2;
   
   // insert elements from 1 to 9
   for (int i=1; i<=9; ++i) {
       coll1.push_back(i);
   }
   // resize destination to have enough room for the overwriting algorithm
   coll2.resize (coll1.size());
   /* copy elements from first into second collection
    * - overwrites existing elements in destination
    */
   copy (coll1.begin(), coll1.end(),     // source
         coll2.begin());                 // destination
   /* create third collection with enough room
    * - initial size is passed as parameter
    */
   deque<int> coll3(coll1.size());
   // copy elements from first into third collection
   copy (coll1.begin(), coll1.end(),     // source
         coll3.begin());                 // destination

}


 </source>


Display all elements in a vector

<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.
*/
  1. include <iostream>
  2. include <vector>
  3. include <string>
  4. include <algorithm>
  5. include <iterator>

using namespace std; int main() {

   // create empty vector for strings
   vector<string> sentence;
   // reserve memory for five elements to avoid reallocation
   sentence.reserve(5);
   // append some elements
   sentence.push_back("Hello,");
   sentence.push_back("how");
   sentence.push_back("are");
   sentence.push_back("you");
   sentence.push_back("?");
   // print elements separated with spaces
   copy (sentence.begin(), sentence.end(),
         ostream_iterator<string>(cout," "));
   cout << endl;

} /* Hello, how are you ?

*/        
   
 </source>


Displaying a Container"s Elements on the Standard Output with copy function

<source lang="cpp">

  1. include <algorithm>
  2. include <iostream>
  3. include <iterator>
  4. include <string>
  5. include <vector>

using namespace std; int main( ) {

  vector<int> v( 5, 9 );
  copy( v.begin(), v.end(), ostream_iterator<int>( cout, " " ) );
  copy( v.begin(), v.end(), ostream_iterator<int>( cout, "\n" ) );

}


 </source>


Print all elements in a list with copy function

<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.
*/
  1. include <iostream>
  2. include <list>
  3. include <algorithm>
  4. include <iterator>

using namespace std; void printLists (const list<int>& l1, const list<int>& l2) {

   cout << "list1: ";
   copy (l1.begin(), l1.end(), ostream_iterator<int>(cout," "));
   cout << endl << "list2: ";
   copy (l2.begin(), l2.end(), ostream_iterator<int>(cout," "));
   cout << endl << endl;

} int main() {

   // create two empty lists
   list<int> list1, list2;
   // fill both lists with elements
   for (int i=0; i<6; ++i) {
       list1.push_back(i);
       list2.push_front(i);
   }
   printLists(list1, list2);

} /* list1: 0 1 2 3 4 5 list2: 5 4 3 2 1 0

*/        
   
 </source>


Use copy function to print all elements in a deque

<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.
*/
  1. include <iostream>
  2. include <deque>
  3. include <string>
  4. include <algorithm>
  5. include <iterator>

using namespace std; int main() {

   // create empty deque of strings
   deque<string> coll;
   // insert several elements
   coll.assign (3, string("string"));
   coll.push_back ("last string");
   coll.push_front ("first string");
   // print elements separated by newlines
   copy (coll.begin(), coll.end(),
         ostream_iterator<string>(cout,"\n"));
   cout << endl;

} /* first string string string string last string

*/        
   
 </source>


Use copy to copy elements in one container to another container

<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.
*/
  1. include <iostream>
  2. include <vector>
  3. include <deque>
  4. include <list>
  5. include <set>
  6. include <map>
  7. include <string>
  8. include <algorithm>
  9. include <iterator>
  10. include <functional>
  11. include <numeric>

using namespace std; /* 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);
   }

} int main() {

   vector<int> coll1;
   list<int> coll2;
   INSERT_ELEMENTS(coll1,1,9);
   /* copy elements of coll1 into coll2
    * - use back inserter to insert instead of overwrite
    */
   copy (coll1.begin(), coll1.end(),         // source range
         back_inserter(coll2));              // destination range
   /* print elements of coll2
    * - copy elements to cout using an ostream iterator
    */
   copy (coll2.begin(), coll2.end(),         // source range
         ostream_iterator<int>(cout," "));   // destination range
   cout << endl;

} /* 1 2 3 4 5 6 7 8 9

*/        
   
 </source>


Use copy to copy elements of one container into another container in reverse order

<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.
*/
  1. include <iostream>
  2. include <vector>
  3. include <deque>
  4. include <list>
  5. include <set>
  6. include <map>
  7. include <string>
  8. include <algorithm>
  9. include <iterator>
  10. include <functional>
  11. include <numeric>

using namespace std; /* 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);
   }

} int main() {

   vector<int> coll1;
   list<int> coll2;
   INSERT_ELEMENTS(coll1,1,9);
   /* copy elements of coll1 into coll2
    * - use back inserter to insert instead of overwrite
    */
   copy (coll1.begin(), coll1.end(),         // source range
         back_inserter(coll2));              // destination range
   /* copy elements of coll1 into coll2 in reverse order
    * - now overwriting
    */
   copy (coll1.rbegin(), coll1.rend(),       // source range
         coll2.begin());                     // destination range
   // print elements of coll2 again
   copy (coll2.begin(), coll2.end(),         // source range
         ostream_iterator<int>(cout," "));   // destination range
   cout << endl;

} /* 9 8 7 6 5 4 3 2 1

*/
       
   
 </source>


Use copy to fill values to an array

<source lang="cpp">

  1. include <algorithm>
  2. include <iostream>
  3. include <iterator>

using namespace std; int main( ) {

  const int num_costs = 4;
  const float cost[num_costs] = { 4.11, 6.77, 8.88, 9.22 };
  copy( cost, cost + num_costs,ostream_iterator<float>( cout, "     " ) );
  const char* fruit[] = { "A", "B", "C" };
  copy( fruit, fruit + sizeof( fruit ) / sizeof( fruit[0] ),
     ostream_iterator<const char*>( cout, "    " ) );
  int year[] = { 2001, 2002, 2003, 2004, 2005 };
  const int num_years = sizeof( year ) / sizeof( year[0] );
  copy( year, year + num_years,ostream_iterator<int>( cout, "    " ) );
  sort( year, year + num_years );
  copy( year, year + num_years,ostream_iterator<int>( cout, "    " ) );
  reverse( year, year + num_years );
  copy( year, year + num_years,ostream_iterator<int>( cout, "    " ) );

}


 </source>


Use copy to output all elements in a container

<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.
*/
  1. include <iostream>
  2. include <vector>
  3. include <deque>
  4. include <list>
  5. include <set>
  6. include <map>
  7. include <string>
  8. include <algorithm>
  9. include <iterator>
  10. include <functional>
  11. include <numeric>

using namespace std; /* 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);
   }

} int main() {

   vector<int> coll1;
   list<int> coll2;
   INSERT_ELEMENTS(coll1,1,9);
   /* copy elements of coll1 into coll2
    * - use back inserter to insert instead of overwrite
    */
   copy (coll1.begin(), coll1.end(),         // source range
         back_inserter(coll2));              // destination range
   /* print elements of coll2
    * - copy elements to cout using an ostream iterator
    */
   copy (coll2.begin(), coll2.end(),         // source range
         ostream_iterator<int>(cout," "));   // destination range
   cout << endl;

} /* 1 2 3 4 5 6 7 8 9

*/        
   
 </source>


Use std::copy to print all elements in a set

<source lang="cpp">

  1. include <iostream>

using std::cout; using std::endl;

  1. include <set>
  2. include <algorithm>
  3. include <iterator> // ostream_iterator

int main() {

  double a[ 5 ] = { 2.1, 4.2, 9.5, 2.1, 3.7 };
  std::set< double, std::less< double > > doubleSet( a, a + 5 );;
  std::ostream_iterator< double > output( cout, " " );
  cout << "doubleSet contains: ";
  std::copy( doubleSet.begin(), doubleSet.end(), output );
  cout << endl;
  return 0;

} /* doubleSet contains: 2.1 3.7 4.2 9.5

*/        
   
 </source>


Use the copy algorithms: Shift the contents of vector1 left by 4 positions

<source lang="cpp">

  1. include <iostream>
  2. include <cassert>
  3. include <algorithm>
  4. include <vector>
  5. include <string>
  6. include <iostream>

using namespace std; int main() {

 string s("abcdefghihklmnopqrstuvwxyz");
 vector<char> vector1(s.begin(), s.end());
 copy(vector1.begin() + 4, vector1.end(), vector1.begin());
 vector<char>::iterator pos;
 for (pos=vector1.begin(); pos!=vector1.end(); ++pos) {
       cout << *pos << " ";
 }
 return 0;

} /* e f g h i h k l m n o p q r s t u v w x y z w x y z

*/        
   
 </source>


Use the generic copy to duplicate vectors

<source lang="cpp">

  1. include <iostream>
  2. include <cassert>
  3. include <algorithm>
  4. include <vector>
  5. include <string>
  6. include <iostream>

using namespace std; int main() {

 string s("abcdefghihklmnopqrstuvwxyz");
 vector<char> vector1(s.begin(), s.end());
 vector<char> vector2(vector1.size());
 // Copy vector1 to vector2:
 copy(vector1.begin(), vector1.end(), vector2.begin());
 assert (vector1 == vector2);
 vector<char>::iterator pos;
 for (pos=vector1.begin(); pos!=vector1.end(); ++pos) {
       cout << *pos << " ";
 }
 cout << "\n\n\n\n";
 for (pos=vector2.begin(); pos!=vector2.end(); ++pos) {
       cout << *pos << " ";
 }
 return 0;

} /* a b c d e f g h i h k l m n o p q r s t u v w x y z

a b c d e f g h i h k l m n o p q r s t u v w x y z

*/        
   
 </source>