How to find the maximum element in a dynamic array using std::max_element() ?

    1 answer 1

    You need to know the size of the array.

    For example, if you created a dynamic array, as shown below.

     #include <algorithm> //... size_t n = 10; int *a = new int[n]; // заполнение значениями элементов массива int *max = std::max_element( a, a + n ); if ( max != a + n ) { std::cout << "The maximum element is equal to " << *max << std::endl; } 

    Or you can declare an iterator using the auto specifier.

      auto max = std::max_element( a, a + n ); 

    In this particular case, there is no need to check that the maximum element is found. But in the general case, when you a priori do not know what the value of the variable n , then such a test is best done.

    To determine the position of a found element, you can, in principle, simply subtract the beginning of the array from the iterator found, such as

     auto pos = max - a; 

    However, from the point of view of programming style, it is better to use the standard function std::distance , declared in the header <iterator> . For example,

     #include <iterator> //... auto = std::distance( a, max ); 

    This makes your code more flexible, since you can replace the array, for example, with some standard container that does not have direct access iterators, and the code will still work.

    • (max bracket got lost somewhere or should it be so? - Grundy
    • and n it is not necessary to multiply by sizeof (int)? - user227927
    • one
      @Grundy Thank you. This is a missprint. - Vlad from Moscow
    • @ user227927 No, it is not necessary, since pointer arithmetic is in effect. The expression a + n points to the place after the last element of the array, that is, it thereby sets the range. - Vlad from Moscow