3

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;

}
Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
Viktoria
  • 533
  • 2
  • 7
  • 24

1 Answers1

8

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

Community
  • 1
  • 1
Davide Spataro
  • 7,319
  • 1
  • 24
  • 36