0

I'm trying to find the maximum value of a vector using std::max_element. When I run the program I get a segmentation fault that I believe is to do with std::end going over the end of the vector? I've tried changing it to std::end(tempdata)-1) but to no avail.

    auto max = std::max_element(std::begin(tempdata), std::end(tempdata));
    std::ofstream maxcurrent("maxcurrent.txt", std::ios::app);
    maxcurrent << v << std::setw(15) << *max << std::endl;

Having looked at this answer I don't see why mine isn't working.

Community
  • 1
  • 1
oxidising
  • 171
  • 2
  • 16

1 Answers1

5

It won't work when max is std::end(tempdata) which can occurs if your tempdata is empty.

Iterator to the greatest element in the range [first, last). If several elements in the range are equivalent to the greatest element, returns the iterator to the first such element. Returns last if the range is empty.

source

Johan
  • 3,728
  • 16
  • 25