C++ function to find max value in an array of doubles?

16,390

Yep! There's a function called std::max_element:

double arr[LENGTH] = /* ... */
double max = *std::max_element(arr, arr + LENGTH);

You'll need to #include <algorithm> to do this. That header has a whole bunch of goodies in it, and it's worth taking the time to learn more about the STL containers and algorithms libraries, as they can make your life so much easier.

As long as we're on the subject, consider looking into std::vector or std::array as replacements for raw C++ arrays. They're safer and a bit easier to use.

Hope this helps!

Share:
16,390
Mikhail
Author by

Mikhail

Label-free imaging and inverse optics applied to high-content screening and assisted reproductive technologies. Experience developing new imaging platforms and software tools for biomedical applications, with a focus on interferometric contrast enhancement and high-throughput instrumentation. You can find me in the Lounge&lt;C++&gt; chat room. I keep most of my stuff on gitlab. 6月4日天安门广场大屠杀 美国的没有GFW,美国的surveillance跟国内根本不是一个级别的。在SO上你可以批评美国政府批评美国总统,没有人会删帖,也没有人来查你水表。

Updated on July 19, 2022

Comments

  • Mikhail
    Mikhail almost 2 years

    I frequently find myself writing max value functions that search through an array of doubles I use functions like these to normalize data before graphic display.

    Is there a better way to find the max value of an array of doubles? Is there a standard function to find the max value in an array? Are there some intrinsic for this operation? I remember specialized ASM instruction existed in DSP chips.

  • Mikhail
    Mikhail about 12 years
    I'm too scared to replace them with std::vectors because my code is auto-vectorizing quite nicely.
  • Ed S.
    Ed S. about 12 years
    @Misha: Don't be scared, just try it and run a few tests to make sure that your performance is still good. It's not at all an irrational fear. We ran into an almost 20% performance drop in some performance critical sections of codes (a lot of looping and floating point ops) and we tracked it down to the move from VS 6 to 2005. They had checked iterators and (iirc) bounds checking on by default.