Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL List calculate average

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.

like image 260
xsl Avatar asked Nov 27 '22 21:11

xsl


2 Answers

Few things:

  1. You don't return anything. (add return avg;)
  2. The -> 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)
  3. The iterator should be a 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.

like image 146
Peter Alexander Avatar answered Dec 08 '22 10:12

Peter Alexander


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.

like image 21
PierreBdR Avatar answered Dec 08 '22 10:12

PierreBdR