mardi 26 novembre 2019

How to find the max element using a list with lambda funcion in C++?

How can I get the max value using a list in C++?

I haven't found solutions for this on Google :(

That Point will be the greatest which coordinates sum is the highest.

Here's the main.cpp where i have to call the lambda function:

PointList plist{Point(1,2,3),
                Point(5.5,4.2,-6.6),
                Point(-2.2,9.7,7),
                Point(7,6.4,9.5),
                Point(8.3,-3,2.4),
                Point(-7.5,-7,1.3),
                Point(5.4,8,3)};
cout << "listsize: " << plist.size() << endl; // listsize: 7

PointList::const_iterator iter1=plist.findMax([](){});

cout << "--Max--  x: " << iter1->getX() << " y: " << iter1->getY() << " z: " << iter1->getZ() << endl; // --Max--  x: 7 y: 6.4 z: 9.5

And here is the findMax function:

PointList::const_iterator PointList::findMax(function<double (const Point &)> func) const
{
    if (size()==0) return cend();
    const_iterator maxit=cbegin();
    double maxval=func(*maxit);
    for (const_iterator temp_it=cbegin(); temp_it!=cend(); ++temp_it)
    {
        double temp_val=func(*temp_it);
        if (temp_val > maxval)
        {
            maxval=temp_val;
            maxit=temp_it;
        }
    }
    return maxit;
}

Here's the full code: https://www.codepile.net/pile/b9e16D9P

Aucun commentaire:

Enregistrer un commentaire