I have to correct some C++/STL code. Unfortunately I have very little C++ experience and know nothing about STL. Nevertheless I finished most of it, but the function below is still giving me problems:
C++ source:
double MyClass::CalculateAvg(const std::list<double> &list)
{
double avg = 0;
std::list<int>::iterator it;
for(it = list->begin(); it != list->end(); it++) avg += *it;
avg /= list->size();
}
C++ header:
static double CalculateAvg(const std::list<int> &list);
It's most likely meant to calculate the average value from a list, but it complies with a lot of errors. I tried to search for a solutions on the web, but I couldn't find anything. I would be glad if someone could help me out.
Update: Thank you for your quick replies. The accepted answer solved all my problems.
Few things:
return avg;
)->
operator is for pointers to objects. You have a reference to a list, so you use list.begin()
and not list->begin()
(same for other member functions)const_iterator
, not iterator
.In any case, you should just do the following:
return std::accumulate(list.begin(), list.end(), 0.0) / list.size();
Optionally checking for list.size() == 0
if that is possible in your use cases.
So, the first error is there:
std::list<int>::iterator it;
You define an iterator on a list of integers, and use it to iterate on a list of doubles. Also, an iterator can only be used on a non-constant list. You need a constant operator. You should write:
std::list<double>::const_iterator it;
At last, you forgot to return the value.
edit: I didn't see, but you pass the list as reference, but use it as a pointer. So replace all the list->
by list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With