Search code examples
c++listminimum

std::min_element on list does not return the minimum


I have a while loop that initialize a list with some doubles.

I would like to output the smallest value but what I have done so far seem not be working, because I don't get any output.

This is the relevant part of my code:

    list<double> allDistances;

    std::ifstream infile("ATXTFile.txt");
    while (std::getline(infile, data)) {

        //do some stuff
        //dist are some double values
        allDistances.push_back(dist);
    }

    cout << min_element(allDistances.begin(), allDistances.end()) << endl;

}

Solution

  • The problem is in the way you print the minimum

    The following will work: cout << *min_element(allDistances.begin(), allDistances.end()) << endl;

    Why?

    Because min_element returns an iterator to the minimum not the minimum itself. If you need the actual value, you had to dereference the iterator returned by min_element.

    You can see it from the documentation that the signature of min_element is:

    template< class ForwardIt > 
    ForwardIt min_element( ForwardIt first, ForwardIt last );
    

    and that it returns a ForwardIt i.e. a forward iterator