Search code examples
c++liststlaverage

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.


Solution

  • 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.