Thread: MSDN for_each sample

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    1,579

    MSDN for_each sample

    Hello everyone,


    I do not know why in for_each sample of MSDN, operator double() is invoked. Which statement triggers operator double()?

    http://msdn2.microsoft.com/en-us/lib...9k(VS.71).aspx

    Code:
    #include <vector>
    #include <algorithm>
    #include <iostream>
    
    // The function object to determine the average
    class Average
    {
    private:
       long num;      // The number of elements
       long sum;      // The sum of the elements
    public:
       // Constructor initializes the value to multiply by
       Average ( ) : num ( 0 ) , sum ( 0 )
       {
       }
    
       // The function call to process the next elment
       void operator ( ) ( int elem ) \
       {
          num++;      // Increment the element count
          sum += elem;   // Add the value to the partial sum
       }
    
       // return Average
       operator double ( )
       {
          return  static_cast <double> (sum) /
          static_cast <double> (num);
       }
    };
    
    int main( )
    {
       using namespace std;
       vector <int> v1;
       vector <int>::iterator Iter1;
    
       // Constructing vector v1
       int i;
       for ( i = -4 ; i <= 2 ; i++ )
       {
          v1.push_back(  i );
       }
    
       // The local state of a function object can accumulate
       // information about a sequence of actions that the
       // return value can make available, here the Average
       double avemod2 = for_each ( v1.begin ( ) , v1.end ( ) ,
          Average ( ) );
       cout << "The average of the elements of v1 is:\n Average ( v1mod2 ) = "
            << avemod2 << "." << endl;
    }

    thanks in advance,
    George

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    ave_mod2 is double so the compiler will try to keep the entire line double, thus calls the double operator from what I can tell.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. MSDN template sample
    By George2 in forum C++ Programming
    Replies: 12
    Last Post: 03-11-2008, 03:47 AM
  2. extern sample in MSDN
    By George2 in forum C++ Programming
    Replies: 6
    Last Post: 02-13-2008, 08:53 AM
  3. MSDN volatile sample
    By George2 in forum C++ Programming
    Replies: 38
    Last Post: 01-05-2008, 06:59 AM
  4. MSDN const_cast sample
    By George2 in forum C++ Programming
    Replies: 7
    Last Post: 12-17-2007, 08:32 AM
  5. MSDN OLE DB Sample Provider entry point
    By George2 in forum C++ Programming
    Replies: 0
    Last Post: 07-21-2007, 07:30 AM