C++/STL Algorithms Non modifying sequence operations/for each

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

A function object that computes an integer sum.

  
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
class sum : unary_function<int, void> {
public:
  argument_type sum;
  sum() { sum = 0; }
  result_type operator()(argument_type i) {
  sum += i;
  }
};
int main()
{
  vector<int> v;
  for(int i=1; i < 11; i++) v.push_back(i);
  for(unsigned i=0; i < v.size(); ++i){
    cout << v[i] << endl;
  }
  sum s;
  s = for_each(v.begin(), v.end(), sum());
  cout << "sum of v: " << s.sum << endl;
  return 0;
}


Call custom function in for_each

  
 
/* 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;
// function object that adds the value with which it is initialized
template <class T>
class AddValue {
  private:
    T theValue;    // value to add
  public:
    // constructor initializes the value to add
    AddValue (const T& v) : theValue(v) {
    }
    // the function call for the element adds the value
    void operator() (T& elem) const {
        elem += theValue;
    }
};
int main()
{
    vector<int> coll;
    INSERT_ELEMENTS(coll,1,9);
    // add ten to each element
    for_each (coll.begin(), coll.end(),       // range
              AddValue<int>(10));             // operation
    PRINT_ELEMENTS(coll);
    // add value of first element to each element
    for_each (coll.begin(), coll.end(),       // range
              AddValue<int>(*coll.begin()));  // operation
    PRINT_ELEMENTS(coll);
}
/* 
11 12 13 14 15 16 17 18 19
22 23 24 25 26 27 28 29 30
 */


Extends a unary_function

  
#include <algorithm>
#include <functional>
#include <vector>
#include <iostream>
using namespace std;
class MinMax : public unary_function<int, void>{
public:
  MinMax();
  void operator()(int elem);
  int min, max;
protected:
  bool first;
};
MinMax::MinMax() : min(-1), max(-1), first(true){}
void MinMax::operator()(int elem){
  if (first) {
    min = max = elem;
  } else if (elem < min) {
    min = elem;
  } else if (elem > max) {
    max = elem;
  }
  first = false;
}
int main(int argc, char** argv){
  vector<int> myVector;
  myVector.push_back(1);
  myVector.push_back(2);
  myVector.push_back(3);
  MinMax func;
  func = for_each(myVector.begin(), myVector.end(), func);
  cout << "The max is " << func.max << endl;
  cout << "The min is " << func.min << endl;
  return (0);
}


Extends unary_function to do sum

  
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
class sum : unary_function<int, void> {
public:
  argument_type sum;
  sum() { sum = 0; }
  result_type operator()(argument_type i) {
    sum += i;
  }
};
int main()
{
  vector<int> v;
  for(int i=1; i < 11; i++) v.push_back(i);
  for(unsigned i=0; i < v.size(); ++i)
    cout << v[i] << endl;
  sum s;
  s = for_each(v.begin(), v.end(), sum());
  cout << "sum of v: " << s.sum << endl;
  v[4]= 99;
  s = for_each(v.begin(), v.end(), sum());
  cout << "sum of v is now: " << s.sum;
  return 0;
}


Use custom function and for_each to calculate mean value

  
 
/* 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;
// function object to process the mean value
class MeanValue {
  private:
    long num;    // number of elements
    long sum;    // sum of all element values
  public:
    // constructor
    MeanValue () : num(0), sum(0) {
    }
    // function call
    // - process one more element of the sequence
    void operator() (int elem) {
        num++;          // increment count
        sum += elem;    // add value
    }
    // return mean value (implicit type conversion)
    operator double() {
        return static_cast<double>(sum) / static_cast<double>(num);
    }
};
int main()
{
    vector<int> coll;
    INSERT_ELEMENTS(coll,1,8);
    // process and print mean value
    double mv = for_each (coll.begin(), coll.end(),  // range
                          MeanValue());              // operation
    cout << "mean value: " << mv << endl;
}
/* 
mean value: 4.5
 */


Use for_each function to add first element to each element in the list

  
 
/* 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 <list>
#include <algorithm>
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;
}

// function object that adds the value with which it is initialized
class AddValue {
  private:
    int theValue;    // the value to add
  public:
    // constructor initializes the value to add
    AddValue(int v) : theValue(v) {
    }
    // the ""function call"" for the element adds the value
    void operator() (int& elem) const {
        elem += theValue;
    }
};
int main()
{
    list<int> coll;
    // insert elements from 1 to 9
    for (int i=1; i<=9; ++i) {
        coll.push_back(i);
    }
    PRINT_ELEMENTS(coll,"initialized:                ");
    // add value of first element to each element
    for_each (coll.begin(), coll.end(),    // range
              AddValue(*coll.begin()));    // operation
    PRINT_ELEMENTS(coll,"after adding first element: ");
}
/* 
initialized:                1 2 3 4 5 6 7 8 9
after adding first element: 2 3 4 5 6 7 8 9 10
 */


Use for_each function to add value for each element

  
 
/* 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 <list>
#include <algorithm>
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;
}

// function object that adds the value with which it is initialized
class AddValue {
  private:
    int theValue;    // the value to add
  public:
    // constructor initializes the value to add
    AddValue(int v) : theValue(v) {
    }
    // the ""function call"" for the element adds the value
    void operator() (int& elem) const {
        elem += theValue;
    }
};
int main()
{
    list<int> coll;
    // insert elements from 1 to 9
    for (int i=1; i<=9; ++i) {
        coll.push_back(i);
    }
    PRINT_ELEMENTS(coll,"initialized:                ");
    // add value 10 to each element
    for_each (coll.begin(), coll.end(),    // range
              AddValue(10));               // operation
    PRINT_ELEMENTS(coll,"after adding 10:            ");
}
/* 
initialized:                1 2 3 4 5 6 7 8 9
after adding 10:            11 12 13 14 15 16 17 18 19
 */


Use for_each function to print all elements in a vector

  
 
/* 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 <algorithm>
using namespace std;
// function that prints the passed argument
void print (int elem)
{
    cout << elem << " ";
}
int main()
{
    vector<int> coll;
    // insert elements from 1 to 9
    for (int i=1; i<=9; ++i) {
        coll.push_back(i);
    }
    // print all elements
    for_each (coll.begin(), coll.end(),    // range
              print);                      // operation
    cout << endl;
}
/* 
1 2 3 4 5 6 7 8 9
 */


Use for_each with predicate

  
 
#include <iostream>
using std::cout;
using std::endl;
#include <algorithm>
#include <numeric>
#include <vector>
#include <iterator>
void outputSquare( int );
int main()
{
  std::ostream_iterator< int > output( cout, " " );
   int a2[ 10 ] = { 100, 2, 8, 1, 50, 3, 8, 8, 9, 10 };
   std::vector< int > v2( a2, a2 + 10 ); // copy of a2
   cout << "Vector v2 contains: ";
   std::copy( v2.begin(), v2.end(), output );
   // output square of every element in v
   cout << "\n\nThe square of every integer in Vector v is:\n";
   std::for_each( v2.begin(), v2.end(), outputSquare );
   cout << endl;
   return 0;
}
void outputSquare( int value )
{
   cout << value * value << " ";
}
/* 
Vector v2 contains: 100 2 8 1 50 3 8 8 9 10
The square of every integer in Vector v is:
10000 4 64 1 2500 9 64 64 81 100
 */