MSDN for_each sample

G

George2

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/library/e5sk9w9k(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
 
D

Daniel T.

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

for_each returns an Average object which is cast into a double (using
operator double()) in order to assign to avemod2.

Personally I wouldn't do it that way, I would create a "Result()"
function and call it.
 
A

Abhishek Padmanabh

// The function object to determine the average

Apart from the context of the sample, you would be better off using
std::accumulate to get the sum and then divide it with the count of
elements. That would be a better, more intuitive/clearer way to
calculate 'average'.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,961
Messages
2,570,131
Members
46,689
Latest member
liammiller

Latest Threads

Top