473,387 Members | 1,585 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

computing average value

I'm trying to get average value. My first attempt is:

#include <...>

template <typename T>
struct avg : public unary_function<T, void>
{
T sum, count;
avg() : sum(0), count(0) {}
void operator()(T value) { sum+=value; ++count; }
T result() { return sum / count; }
};

int main()
{
const int N = 4;
double arr[N] = { 1, 2, 3, 4 };
avg<double> res = std::for_each(arr, arr+N, avg<double>());
std::cout << "avg=" << res.result() << std::endl;
}

Questions are:
1. Is for_each a right way? May be I should use accumulate or
something?
2. ": public unary_function<T, void>" is not nessesary. Should I use it
anyway?

Raider

Feb 26 '06 #1
5 2177
"Raider" <sr*****@yandex.ru> wrote in message
news:11**********************@z34g2000cwc.googlegr oups.com...
: I'm trying to get average value. My first attempt is:
:
: #include <...>
:
: template <typename T>
: struct avg : public unary_function<T, void>
: {
: T sum, count;
: avg() : sum(0), count(0) {}
: void operator()(T value) { sum+=value; ++count; }
: T result() { return sum / count; }
: };
:
: int main()
: {
: const int N = 4;
: double arr[N] = { 1, 2, 3, 4 };
: avg<double> res = std::for_each(arr, arr+N, avg<double>());
: std::cout << "avg=" << res.result() << std::endl;
: }
:
: Questions are:
: 1. Is for_each a right way? May be I should use accumulate or
: something?

I have to say that my first instinct would be to use (in main):
double avg = std::accumulate( arr, arr+N, 0 ) / N;
Only if the item count is unknown would you need a special class.

I think that a problem with for_each is that you have no
guarantee that the algorithm won't create copies of the
provided function object.
So std::accumulate would be safer. You could eventually use
a custom predicate, and an accumulation value of type
std::pair<double,unsigned> -- sum and count -- or similar.

: 2. ": public unary_function<T, void>" is not nessesary.
: Should I use it anyway?
It is probably a good habit to take, as it will be useful for
some more advanced generic programming techniques.
hth -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Feb 26 '06 #2
Ivan Vecerina wrote:
"Raider" <sr*****@yandex.ru> wrote in message
news:11**********************@z34g2000cwc.googlegr oups.com...
: I'm trying to get average value. My first attempt is:
:
: #include <...>
:
: template <typename T>
: struct avg : public unary_function<T, void>
: {
: T sum, count;
: avg() : sum(0), count(0) {}
: void operator()(T value) { sum+=value; ++count; }
: T result() { return sum / count; }
: };
:
: int main()
: {
: const int N = 4;
: double arr[N] = { 1, 2, 3, 4 };
: avg<double> res = std::for_each(arr, arr+N, avg<double>());
: std::cout << "avg=" << res.result() << std::endl;
: }
:
: Questions are:
: 1. Is for_each a right way? May be I should use accumulate or
: something?

I have to say that my first instinct would be to use (in main):
double avg = std::accumulate( arr, arr+N, 0 ) / N;
Only if the item count is unknown would you need a special class.

I think that a problem with for_each is that you have no
guarantee that the algorithm won't create copies of the
provided function object.


My understanding of the standard is that this guarantee actually is made:

[25.1.1]

template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f);
Effects: Applies f to the result of dereferencing every iterator in the
range [first, last), starting from first and proceeding to
last - 1.
Returns: f.
Complexity: Applies f exactly last - first times.
Notes: If f returns a result, the result is ignored.

As I read this paragraph, "f" denotes the function object passed. The only
copy that is made is in passing the object by value. Other than that, you
should be safe. Besides:

(a) If copies were to be made, the return of f would not make sense. This
hook is provided to pass back information that the function object may
collect during its pass over the objects in the sequence.

(b) If this is *not* the intended meaning of the standard, that should
qualify as a bug in the standard.
[snip]
Best

Kai-Uwe Bux
Feb 26 '06 #3
"Kai-Uwe Bux" <jk********@gmx.net> wrote in message
news:dt**********@murdoch.acc.Virginia.EDU...
: Ivan Vecerina wrote:
....
: > I think that a problem with for_each is that you have no
: > guarantee that the algorithm won't create copies of the
: > provided function object.
:
: My understanding of the standard is that this guarantee actually is
made:
:
: [25.1.1]
:
: template<class InputIterator, class Function>
: Function for_each(InputIterator first, InputIterator last, Function f);
: Effects: Applies f to the result of dereferencing every iterator in the
: range [first, last), starting from first and proceeding to
: last - 1.
: Returns: f.
: Complexity: Applies f exactly last - first times.
: Notes: If f returns a result, the result is ignored.
:
: As I read this paragraph, "f" denotes the function object passed. The
only
: copy that is made is in passing the object by value. Other than that,
you
: should be safe.

Right -- I'm afraid that I confused for_each with other algorithms.
for_each
is actually the one that provides the most guarantees regarding side
effects
and order of execution. See for example the following discussion:
http://www.angelikalanger.com/Articl...Transform.html
Thank you for the correction,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Feb 26 '06 #4
In article <11**********************@z34g2000cwc.googlegroups .com>,
"Raider" <sr*****@yandex.ru> wrote:
I'm trying to get average value. My first attempt is:

#include <...>

template <typename T>
struct avg : public unary_function<T, void>
{
T sum, count;
'sum' above probably shouldn't be of type T
avg() : sum(0), count(0) {}
void operator()(T value) { sum+=value; ++count; }
T result() { return sum / count; }
};

int main()
{
const int N = 4;
double arr[N] = { 1, 2, 3, 4 };
avg<double> res = std::for_each(arr, arr+N, avg<double>());
std::cout << "avg=" << res.result() << std::endl;
}

Questions are:
1. Is for_each a right way? May be I should use accumulate or
something?
Although for_each works, I'd be inclined to use accumulate. What you are
doing is accumulating the total of the items and the number of items,
then doing a divide on them...

template < typename T >
pair<T, int> avg_accum( const std::pair<T, int>& prev, T next )
{
return make_pair( prev.first + next, prev.second + 1 );
}

pair< double, int > p = accumulate( arr, arr + N, make_pair( 0.0, 0 ),
&avg_accum<double> );
cout << "avg2 = " << (p.first/p.second) << '\n';
Of course in your particular case, you already know the number of items
so you could just use the specialized form of accumulate, but the above
will even work for input iterators, whereas the specialized form would
not.

2. ": public unary_function<T, void>" is not nessesary. Should I use it
anyway?


I think it's good to be in the habit of using them, it communicates
intent, and is useful for functor composition.
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 26 '06 #5
> 'sum' above probably shouldn't be of type T

I think it must be as follows:

typename T sum;
int count;

And thanks for the rest feedback!

Raider

Feb 27 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Tony Lennard | last post by:
I have several queries, which generate about 10 fields each a text field of length 2 (which contain effort and attainment grades), eg A2, B4, A3, A3. I am trying to calculate an 11th fields, which...
5
by: Carlo B | last post by:
I need to store numbers in an array and by using a class I need to calculate the average of the numbers entered. I cannot get the text box to return the total of the numbers in the average function...
3
by: C++Geek | last post by:
I need to get this program to average the salaries. What am I doing wrong? //Program to read in employee data and calculate the average salaries of the emplyees.
1
by: Theadmin77 | last post by:
Well ...this is a real challenge .....i got everything else working OK...but ... I have to get the average and maximum value out of a group of people thru two functions .I have problems passing...
1
by: sadhana123 | last post by:
i have matrix of large data say 1700 row and 500 in coloumn in this there entry is given as rate value from 1- 5 . some values are missing . so i have to find out a predict value for each col value...
3
by: vileoxidation | last post by:
Hello, and thanks for any help in advance! Basically, as the title says, I am looking for a way to print the number of times the user gave the program an input, and then also print the average of...
21
by: Bill Cunningham | last post by:
I have create these 2 files. Called main.c and atr.c. They seem to work pretty well. I just wanted to submit them to see what if any errors others that know more might find. Thanks. atr.c ...
6
by: kumarboston | last post by:
Hi All, I am trying to get an average value for my data, here is my data file DATA FILE EP1934.PDB 250 250 11.27 EP1934.PDB 251 251 12.7332 EP1934.PDB 252 252 6.38341 EP1934.PDB 253 253...
5
by: kumarboston | last post by:
Hi all, I was trying to calculate the average value from different parts of the same data file. For example, if suppose we have number 1 - 10 and i was trying to calculate the average of only first...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.